- LinkedHashSet is Hashtable & linked list implementation of the Set interface, with predictable iteration order.
- 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.
- Given a LinkedHashSet collection in java.
- Set<String> cmputerGenerations = new LinkedHashSet<>();
- We would like to convert LinkedHashSet collection to TreeSet collection in java.
- Convert LinkedHashSet to TreeSet collection.
- TreeSet collection will produce the sorted output.
- We will get sorted output using TreeSet collection.
1. Convert LinkedHashSet of String objects to TreeSet collection (java/example)
package org.learn.collection.set.lhset;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
public class DemoLinkedHashSetToTreeSet {
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("Set: "+ cmputerGenerations);
Set<String> linkedhashSetToTreeSet = new TreeSet<>(cmputerGenerations);
System.out.println("TreeSet:"+linkedhashSetToTreeSet);
}
}
2. Output: LinkedHashSet of String objects to TreeSet collection (java/example)
Set: [VacuumTubes, Transistors, IntegratedCircuits, Microprocessors, ArtificialIntelligence]
TreeSet:[ArtificialIntelligence, IntegratedCircuits, Microprocessors, Transistors, VacuumTubes]