How to convert HashSet to ArrayList
In this post we will see examples to convert HashSet to ArrayList in java.
HashSet and ArrayList are both Collection objects. Hence we can pass HashSet to the construtor of the ArrayList and get it converted.
Example : Convert HashSet to ArrayList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | package com.kscodes.sampleproject; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class HashSetToArrayListEx { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(); hashSet.add("Java"); hashSet.add("Spring"); hashSet.add("Hibernate"); hashSet.add("JavaScript"); System.out.println("Elements in HashSet :: " + hashSet); System.out.println("Size of HashSet :: " + hashSet.size()); // Convert to ArrayList List<String> arrayList = new ArrayList<>(hashSet); System.out.println("Elements in ArrayList :: " + arrayList); System.out.println("Size of ArrayList :: " + arrayList.size()); } } |
Output
1 2 3 4 | Elements in HashSet :: [Hibernate, Spring, JavaScript, Java] Size of HashSet :: 4 Elements in ArrayList :: [Hibernate, Spring, JavaScript, Java] Size of ArrayList :: 4 |