Site icon

Convert LinkedHashSet of String objects to TreeSet collection (java/ example)

  1. LinkedHashSet is Hashtable & linked list implementation of the Set interface, with predictable iteration order.
  2. LinkedHashSet maintains the Insertion order of elements using LinkedList
  3. LinkedHashSet is UnSynchronized and not thread safe.
  4. 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.
  5. Given a LinkedHashSet collection in java.
    • Set<String> cmputerGenerations = new LinkedHashSet<>();
  6. We would like to convert LinkedHashSet collection to TreeSet collection in java.
  7. Convert LinkedHashSet to TreeSet collection.
  8. 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]
Exit mobile version