Signup/Sign In
PUBLISHED ON: JANUARY 27, 2021

Java ArrayList to LinkedHashSet Conversion

In this post, we are going to convert ArrayList to LinkedHashSet. LinkedHashSet is a class that uses linkedlist data structure to implements Set in Java.

It is helpful when we want to convert array-like list to a unique collection of data. LinkedHashSet is used to collect unique data.

To convert ArrayList to LinkedHashSet, we are using various ways like stream API or add() method or LinkedHashSet constructor. See the below examples.

Time for an Example:

In this example, we are using stream API to collect ArrayList elements into LinkedHashSet to get unique elements. See the example below.

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;

public class Main {
	public static void main(String[] args){
		ArrayList<String> arrList = new ArrayList<>();
		arrList.add("Mango");
		arrList.add("Apple");
		arrList.add("Orange");
		arrList.add("Apple");
		System.out.println(arrList);
		// ArrayList to LinkedHashSet
		LinkedHashSet<String> linkList = arrList.stream().collect(Collectors.toCollection(LinkedHashSet::new));
		System.out.println("Linked HashSet:");
		System.out.println(linkList);
	}
}


[Mango, Apple, Orange, Apple]
Linked HashSet:
[Mango, Apple, Orange]

Example:

If you want to add elements one by one to LinkedHashSet, then you can use add() method and get a collection of unique elements. See the example below.

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class Main {
	public static void main(String[] args){
		ArrayList<String> arrList = new ArrayList<>();
		arrList.add("Mango");
		arrList.add("Apple");
		arrList.add("Orange");
		arrList.add("Apple");
		System.out.println(arrList);
		// ArrayList to LinkedHashSet
		LinkedHashSet<String> linkSet = new LinkedHashSet<String>();
		for (String arr : arrList) {
			linkSet.add(arr);
		}
		System.out.println("Linked HashSet:");
		System.out.println(linkSet);
	}
}


[Mango, Apple, Orange, Apple]
Linked HashSet:
[Mango, Apple, Orange]

Example:

This is another approach that you can use to get LinkedHashSet from an ArrayList. Here, we are passing ArrayList as an argument to the constructor of LinkedHashSet.

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class Main {
	public static void main(String[] args){
		ArrayList<String> arrList = new ArrayList<>();
		arrList.add("Mango");
		arrList.add("Apple");
		arrList.add("Orange");
		arrList.add("Apple");
		System.out.println(arrList);
		// ArrayList to LinkedHashSet
		LinkedHashSet<String> linkSet = new LinkedHashSet<String>(arrList);
		System.out.println("Linked HashSet:");
		System.out.println(linkSet);
	}
}


[Mango, Apple, Orange, Apple]
Linked HashSet:
[Mango, Apple, Orange]



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.