How to convert a List to a Set

In this post we will provide an example of how to convert a List to a Set and vice versa (ArrayList to HashSet). This is very easy to do, as the constructor of both objects accept a collection to initialise its value.

How to convert a List to a Set:

The example below shows how to convert an ArrayList to a HashSet. As you can see from the example the HashSet constructor takes the list (collection) as its initial value.

Running the above code produces the following:

How to convert a Set to a List

The example below shows how to convert a HashSet to an ArrayList. As you can see its very easy todo, as the ArrayList can take a collection via the constructor to initialise its value.

Running the above produces the following output:

Similar posts:

  1. Check if array contains a certain value
  2. Check list only contains a certain set of values
  3. How to split a string in Java
  4. CountDownLatch in Java

References:

  1. Java List tutorial
  2. Java List API Documentation
  3. Java Set API Documentation

 

Leave a Reply