Java convert Set to List | ArrayList to HashSet

Java converts Set to List by using many methods like- Loop traverse, ArrayList constructor, addAll method, Java 8 Stream, Guava Library List.newArrayList(set).

Java convert Set to List ArrayList to HashSet

There is one more easiest way to convert Set to List in Java. Both both Set and List are extended the Collection, so converting Set into the list is quite straightforward. It only needed to just pass the value in the constructor. See the below code.

Example: Converting ArrayList to HashSet

Output:

List values …..
2
1
3
Set values …..
1
2
3

Others ways to convert set to list in Java

  • Simple Loop traverse
  • ArrayList constructor
  • addAll method
  • Java 8 Stream
  • Guava Library List.newArrayList(set).

Let’s see the examples

Simple Loop traverse

Use for-Loop or for-each loop to traverse the given set and one by one add elements to the list.

Output:

Created ArrayList is
Java
EyeHunts

ArrayList constructor

Here is simply how you can use an ArrayList and LinkedList constructors.

Output:

Created ArrayList is
1
2
Created LinkedList is
1
2

addAll method

Simply use lsit.addAll method.

Java 8 Stream

Stream method works only in Java 8 or versions after that.

Output: 1
2

Do comment if you knew any other way to do it or any doubts.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java convert Set to List Program codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.