Tuesday, 19 January 2016

3 ways to loop over Set or HashSet in Java? Examples

Since Set interface or HashSet class doesn't provide a get() method to retrieve elements, the only way to take out elements from a Set is to iterate over it by using Iterator, or loop over Set using advanced for loop of Java 5. You can get the iterator by calling the iterator() method of Set interface. This method returns an iterator over the elements in the sets but they are returned in no particular order, as Set doesn't guarantee any order. Though individual Set implementations e.g. LinkedHashSet or TreeSet can impose ordering and in such iterator will return elements on that order. You can only traverse in one direction using iterator i.e. from first to last elements, there is no backward traversing allowed as was the case with List interface and ListIterator. Similarly, if you use advanced for loop, then also you can traverse in only one direction.
Read more »

No comments:

Post a Comment