- Using Iterator –
import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; public class IterateLinkedHashSet { public static void main(String[] args) { Set<String> linkedHashSetObj = new LinkedHashSet(); linkedHashSetObj.add("ram"); linkedHashSetObj.add("mohan"); linkedHashSetObj.add("sohan"); linkedHashSetObj.add("ram"); linkedHashSetObj.add("ram"); Iterator<String> it = linkedHashSetObj.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
Output is –
ram
mohan
sohan
2. Using for-each loop –
import java.util.LinkedHashSet; import java.util.Set; public class IteratingLinkedHashSet2 { public static void main(String[] args) { Set<String> linkedHashSetObj = new LinkedHashSet(); linkedHashSetObj.add("ram"); linkedHashSetObj.add("mohan"); linkedHashSetObj.add("sohan"); linkedHashSetObj.add("ram"); linkedHashSetObj.add("ram"); for (String str : linkedHashSetObj) { System.out.println(str); } } }
Output is –
ram
mohan
sohan
We can’t iterate LinkedHashSet using Listiterator, Enumeration and normal for loop(as we don’t have get() method in LinkedHashSet like ArrayList).