Java 8 – Iterate through Set

In this example, We will show you simple example about, How to Iterate through set in Java 8. The example program has been tested and shared in the same post.

Example Program

package com.dineshkrish;
import java.util.Set;
import java.util.TreeSet;
/**
* 
* @author Dinesh Krishnan
*
*/
public class SetForEach {
public static void main(String[] args) {
// defining the set object
Set<String> names = new TreeSet<String>();
// adding the elements to set
names.add("Dinesh");
names.add("Krishnan");
names.add("John");
names.add("Smith");
names.add("Peter");
// iterating the elements
names.forEach(name -> System.out.println(name));
}
}

Output

Dinesh
John
Krishnan
Peter
Smith

References

1. JavaDoc – Set Interface
2. JavaDoc – TreeSet Class
3. Java 8 – Iterable forEach() method

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *