Convert Collection List to Set using Java 8 Stream API

In Java, the Stream class was introduced as a part of the Java 8 Streams API that provides a functional way of processing collections of objects, i.e. a sequence of elements that can be processed in a functional manner.

With the help of the Stream class, you can perform various operations on collections like filtering, mapping, sorting, reducing, and more, without modifying the original collection.

Converting List to Set using Java 8 Stream API

Let's see the steps,

Step 1: We create a List of Strings (can be any other data type)

Step 2: We make use of the stream() to convert List to Stream.

Step 3: Finally, we make use of the collect() method to collect the Stream as set.

Code Example

package org.example;

import java.util.*;

 * Code Example in Java 8 to convert
 * List to Set using Stream API
public class ListToSet {

    public static void main(String[] args) {

       List<String> citiesList = new ArrayList<>();

        citiesList.add("NYC"); //Duplicates
        citiesList.add("Chicago"); //Duplicates

        System.out.println("List Elements: " + citiesList);

        //Map to List
        Set<String> citiesSet = citiesList
                .stream() //Step 1: Convert Set to Steam
                .collect(Collectors.toSet()); // Step 2: Collect Steam as Set

        System.out.println("Set Elements: " + citiesSet);

List Elements: [NYC, Chicago, Austin, Huston, Ohio, NYC, Chicago]
Set Elements: [Chicago, NYC, Ohio, Austin, Huston]

As you may see in the output, the set does not contain duplicate records.

Output - convert list to set using java 8 stream api

Have Questions? Post them here!

Top Hashtags: