Convert LinkedHashSet collection of String objects to Array in java (example)

  1. Hashtable and 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. Given a LinkedHashSet containing String objects in java.
    • Set<String> computerGenerations = new LinkedHashSet<>()
  5. We would like to convert LinkedHashSet to Array of Strings in java.
    1. We will use toArray of Set interface to achieve the conversion.
    2. We will get output as String[] linkedHashSetToArray.

1. LinkedHashSet collection class hierarchy:

LinkedHashSet class hierarchy
Fig 1: LinkedHashSet class hierarchy

Let us look into the complete code to convert LinkedHashSet of String objects to array in java.

2. Convert LinkedHashSet collection of String objects to Array (java /example)

package org.learn.collection.set.lhset;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

public class DemoLinkedHashSetToArray {

	public static void main(String[] args) {
		Set<String> computerGenerations = new LinkedHashSet<>();
		computerGenerations.add("VacuumTubes");
		computerGenerations.add("Transistors");
		computerGenerations.add("IntegratedCircuits");
		computerGenerations.add("Microprocessors");
		computerGenerations.add("ArtificialIntelligence");	
		
		System.out.println("Set: "+ computerGenerations);
		String[] linkedHashSetToArray = new String[computerGenerations.size()];
		computerGenerations.toArray(linkedHashSetToArray);
		
		System.out.println("Array:"+ Arrays.toString(linkedHashSetToArray));
	}
}

3. OutputĀ – convert LinkedHashSet of String objects to Array in java

Set: [VacuumTubes, Transistors, IntegratedCircuits, Microprocessors, ArtificialIntelligence]
Array:[VacuumTubes, Transistors, IntegratedCircuits, Microprocessors, ArtificialIntelligence]
Scroll to Top