- Given the LinkedHashSet collection of String Objects in java.
- Iterate through the LinkedHashSet collection using java 8 stream. We will demonstrate couple of methods to loop through LinkHashSet in java.
- Iterate through using LinkedHashSet’s Iterator.
- Loop through LinkedHashSet using Java 8 forEach (Lambda Streams).
- LinkedHashSet maintains the Insertion order of elements using LinkedList
- LinkedHashSet is UnSynchronized and not thread safe.
- Iterator of LinkedHashSet is fail-fast.
- Iterator will throw ConcurrentModificationException, if LinkedHashSet modified at any time after the iterator is created, in any way except through the iterator’s own remove method.
- LinkedHashSet offers constant time performance for the basic operations like add, remove, contains and size.
1. LinkedHashSet collection class hierarchy:

2. Iterate LinkedHashSet of string objects – java 8 streams
package org.learn.collection.set.lhset; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; public class DemoIterationLinkedHashSet { public static void main(String[] args) { Set<String> cmputerGenerations = new LinkedHashSet<>(); cmputerGenerations.add( "VacuumTubes" ); cmputerGenerations.add( "Transistors" ); cmputerGenerations.add( "IntegratedCircuits" ); cmputerGenerations.add( "Microprocessors" ); cmputerGenerations.add( "ArtificialIntelligence" ); System.out.println( "Method 1 - Iterate LinkedHashSet: " ); demoIterateLinkedHashSet(cmputerGenerations); System.out.println( "\nMethod 2 - Iterate LinkedHashSet using java 8: " ); demoIterateLinkedHashSetJava8(cmputerGenerations); } private static void demoIterateLinkedHashSet(Set<String> cmputerGenerations) { Iterator<String> iterator = cmputerGenerations.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } private static void demoIterateLinkedHashSetJava8(Set<String> cmputerGenerations) { cmputerGenerations.forEach((key) -> { System.out.println(key); }); } } |
3. Iterate LinkedHashSet of String objects – lambda streams
Method 1 - Iterate LinkedHashSet: VacuumTubes Transistors IntegratedCircuits Microprocessors ArtificialIntelligence Method 2 - Iterate LinkedHashSet using java 8: VacuumTubes Transistors IntegratedCircuits Microprocessors ArtificialIntelligence |