In this post we’ll see how you can iterate any Set implementation like HashSet in Java. To loop through a HashSet you have following options, you can choose based on your requirement or the Java version you are using.
- First option to iterate a HashSet in Java is to use a ForEach loop, if you are just iterating without doing any structural modification (adding or removing element) to the Set then this is the best option to iterate a HashSet.
- Using iterator() method which returns an iterator over the elements in the given Set. If you have to remove any element while iterating then use this option otherwise ConcurrentModificationException will be thrown.
- Java 8 onwards you also have an option to use forEach statement to iterate a HashSet in Java.
Iterating a HashSet – Java example
Let’s see a Java example code which illustrates all of the options mentioned above to loop through a HashSet.
import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class IterateSetDemo { public static void main(String[] args) { // creating a HashSet Set<String> citySet = new HashSet<String>(); // Adding elements citySet.add("London"); citySet.add("Tokyo"); citySet.add("New Delhi"); citySet.add("Beijing"); citySet.add("Nairobi"); System.out.println("-- Iterating HashSet - ForEach loop --"); for(String city : citySet){ System.out.println("city- " + city); } System.out.println("-- Iterating HashSet - using iterator --"); Iterator<String> itr = citySet.iterator(); while(itr.hasNext()){ System.out.println("city- " + itr.next()); } System.out.println("-- Iterating HashSet - using forEach statement-- "); citySet.forEach((city)->System.out.println("city- " + city)); } }
Output
-- Iterating HashSet - ForEach loop -- city- Beijing city- New Delhi city- Nairobi city- Tokyo city- London -- Iterating HashSet - using iterator -- city- Beijing city- New Delhi city- Nairobi city- Tokyo city- London -- Iterating HashSet - using forEach statement-- city- Beijing city- New Delhi city- Nairobi city- Tokyo city- London
That's all for this topic How to Loop Through HashSet in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment