Java - How to convert Set to List and List to Set

Here is an example of converting between Set, List, and Array.

  • Set to List and List to Set
  • List to Array, Array to List
  • Set to Array, Array to Set

In addition, an example using Google`s Java library Guava is also introduced.

To use Guava in a Gradle project, define the dependencies in build.gradle as follows.

implementation("com.google.guava:guava:28.2-jre")

In your Android project, you define it like this:

implementation("com.google.guava:guava:28.2-android")

Convert List to Set

Just pass a List as an argument when creating a Set.

List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = new HashSet<>(sourceList);

Convert List to Set (Guava)

Guava provides Util classes called Lists and Sets. Using this, you can create a List with simple code and convert it to a Set.

List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = Sets.newHashSet(sourceList);

Convert Set to List

Just pass Set as an argument when creating a List.

Set<Integer> sourceSet = new HashSet<>(Arrays.asList(0, 1, 2, 3, 4, 5));
List<Integer> targetList = new ArrayList<>(sourceSet);

Convert Set to List (Guava)

Using Guava`s Lists and Sets, you can easily create and convert them.

Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = Lists.newArrayList(sourceSet);

Convert Array to Set

Stream can be used to convert an Array to a Set.

Integer[] array = {1, 2, 3};
Set<Integer> set = Arrays.stream(array).collect(Collectors.toSet());
System.out.println("Set: " + set);
// Set: [1, 2, 3]

Convert Set to Array

You can easily convert a Set to an Array using Set.toArray().

Set<Integer> set = Sets.newHashSet(1, 2, 3);
Integer[] array = new Integer[set.size()];

set.toArray(array);
System.out.println("Array: " + Arrays.toString(array));
// Array: [1, 2, 3]

Convert Array to List

Stream can be used to convert an Array to a List.

Integer[] array = {1, 2, 3};
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());

Convert List to Array

You can easily convert a List to an Array using List.toArray().

List<Integer> list = Arrays.asList(1, 2, 3);
Integer[] array = new Integer[list.size()];
list.toArray(array);

Reference

codechachaCopyright ©2019 codechacha