Set Interface Example



The Set interface

- contains no duplicate elements

- can contain at most one null element.

- does not provide any ordering guarantees.

The following example explains how to iterate through a Set in various Java versions including Java 8.

             	
package com.smoothexample.java.set; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class SetExample { public static void main(String[] args) { Set<String> set = new HashSet<String>(); populateValues(set); System.out.println("Using for loop"); for (String s : set) { System.out.println(s); } System.out.println("----------------------------------------------------------------------"); System.out.println("Using iterator"); System.out.println("----------------------------------------------------------------------"); Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } System.out.println("----------------------------------------------------------------------"); System.out.println("Using Java8 - Singlestatement in foreach"); System.out.println("----------------------------------------------------------------------"); set.forEach(name -> System.out.println(name)); System.out.println("----------------------------------------------------------------------"); System.out.println("Using Java8 - multiple statements in foreach"); System.out.println("----------------------------------------------------------------------"); set.forEach(name -> { String s = "Printing name " + name; System.out.println(s); }); } private static void populateValues(Set set) { for (int i = 1; i <= 10; i++) { String s = "name" + i; set.add(s); } } }


Sample output


			
			
Using for loop
name6
name5
name4
name3
name9
name10
name8
name7
name2
name1
----------------------------------------------------------------------
Using iterator
----------------------------------------------------------------------
name6
name5
name4
name3
name9
name10
name8
name7
name2
name1
----------------------------------------------------------------------
Using Java8 - Singlestatement in foreach
----------------------------------------------------------------------
name6
name5
name4
name3
name9
name10
name8
name7
name2
name1
----------------------------------------------------------------------
Using Java8 - multiple statements in foreach
----------------------------------------------------------------------
 Printing name name6
 Printing name name5
 Printing name name4
 Printing name name3
 Printing name name9
 Printing name name10
 Printing name name8
 Printing name name7
 Printing name name2
 Printing name name1