In this post we’ll see different ways to iterate a Set or HashSet in Java. Your options to iterate a HashSet are as follows-
- You can use For-Each loop (Advanced or enhanced for loop), available from Java 5.
- You can iterate a HashSet using Iterator. Using
iterator()
method you can get an iterator and then using thehasNext()
andnext()
method of the iterator you can iterate a HashSet. - You can also use
forEach
statement available from Java 8 to loop through Set.
Java HashSet iteration example
Here is a Java example code that shows all of the above mentioned ways to loop a Set in Java.
public class SetIteration { public static void main(String[] args) { Set<String> capitalSet = new HashSet<String>(); // adding elements capitalSet.add("New Delhi"); capitalSet.add("Lisbon"); capitalSet.add("Buenos Aires"); capitalSet.add("Beijing"); System.out.println("**Iterating HashSet using For-Each loop**"); for(String capital : capitalSet){ System.out.println("Capital city- " + capital); } System.out.println("**Iterating using Iterator**"); Iterator<String> itr = capitalSet.iterator(); while(itr.hasNext()){ System.out.println("Capital city- " + itr.next()); } System.out.println("**Iterating using forEach statement**"); capitalSet.forEach((c)->System.out.println("Capital city- " + c)); System.out.println("**Iterating using forEach statement (Method reference)**"); // Using forEach with method reference capitalSet.forEach(System.out::println); } }Output
**Iterating HashSet using For-Each loop** Capital city- Beijing Capital city- New Delhi Capital city- Lisbon Capital city- Buenos Aires **Iterating using Iterator** Capital city- Beijing Capital city- New Delhi Capital city- Lisbon Capital city- Buenos Aires **Iterating using forEach statement** Capital city- Beijing Capital city- New Delhi Capital city- Lisbon Capital city- Buenos Aires **Iterating using forEach statement (Method reference)** Beijing New Delhi Lisbon Buenos Aires
That's all for the topic How to Iterate a Java HashSet. If something is missing or you have something to share about the topic please write a comment.
You may also like
- How to Sort Java HashSet
- How to Synchronize Java HashSet
- How to Iterate Java ArrayList
- How to Iterate a Java HashMap
- Java try-with-resources With Examples
- Check Given Number Palindrome or Not in Java
- Spring @PostConstruct and @PreDestroy Annotation
- React useState Hook With Examples
- Pass Data From Child to Parent Component in React
- Parquet File Format in Hadoop
No comments:
Post a Comment