Tuesday, April 28, 2015

Set Collection


The "java.util.Set" interface is a subtype of the "java.util.Collection" interface that:
  1. Can not contain duplicates.
  2. Allow one null element.
  • Set Implementations:
  1. java.util.EnumSet
  2. java.util.HashSet
  3. java.util.LinkedHashSet
  4. java.util.TreeSet
  5. java.util.SortedSet

HashSet is unordered collection (Doesn't maintains insertion order) , It changes the order of the  inserted elements.

LinkedHashSet guarantees that the order of the elements during iteration is the same as the order they were inserted.

TreeSet guarantees that the order of the elements when iterated is the sorting order of the elements.

  • Operations:
  1. To add elements to a Set you call its add() method.
  2. You remove elements by calling the remove(Object o) method.
Remove Duplicates from a Collection:
Suppose you have a Collection, c, and you want to create another Collection containing the same elements but with all duplicates eliminated:

Collection<Type> noDups = new HashSet<Type>(c); 

In jdk 8 you can remove duplicate using Lambdas:
c.stream().collect(Collectors.toSet()); // no duplicates

  • Iterate Elements:
//access via Iterator
Iterator iterator = setA.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}


//access via new for-loop
for(Object object : setA) {
    String element = (String) object;
}
https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
http://fastlearned.blogspot.com/2012/08/java-collection.html

No comments:

Post a Comment

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...