The "java.util.Set" interface is a subtype of the "java.util.Collection" interface that:
- Can not contain duplicates.
- Allow one null element.
- Set Implementations:
- java.util.EnumSet
- java.util.HashSet
- java.util.LinkedHashSet
- java.util.TreeSet
- 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.
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:
- To add elements to a
Set
you call itsadd()
method. - 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