Site icon

Iterate or loop LinkedHashSet collection of String objects (java8/example)

1. LinkedHashSet collection class hierarchy:

Fig 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
Exit mobile version