Converting HashSet to List in Java: Example and Explanation

  • Last updated Apr 25, 2024

The code in this example provides a demonstration of converting a HashSet to a List in Java. The HashSet is a collection that does not allow duplicate elements and does not maintain any specific order. On the other hand, a List is an ordered collection that allows duplicate elements.

Example:

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

public class Example {

   public static void main(String[] args) {

	HashSet fruitHashSet = new HashSet<>();
	fruitHashSet.add("mango");
	fruitHashSet.add("apple");
	fruitHashSet.add("orange");
	fruitHashSet.add("papaya");
	fruitHashSet.add("coconut");

	// converting from hashset to list
	ArrayList fruitList = (ArrayList) fruitHashSet.stream().collect(Collectors.toList());

	// accessing items using for loop
	for (int i = 0; i < fruitList.size(); i++) {
	    System.out.println(fruitList.get(i));
	}
   }

}

Output:

orange
papaya
apple
mango
coconut