How to convert list into set in java

What we will learn here about java

  • How to convert list into set in java

Here we will see how to convert List into Set in java using stream.

How to convert list into set in java

Below sample program to convert List into Set in java is given beow

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class List2Set {
    public static void main(String[] args) {
        List numbers = new ArrayList();
        numbers.add(10);numbers.add(100);
        numbers.add(15);numbers.add(10);
        numbers.add(1);numbers.add(65);
        numbers.add(55);numbers.add(1);
        System.out.println("List have duplicates");
        System.out.println(numbers);

        System.out.println("Set doesn't have duplicates");
        Set setnumbers = numbers.stream().collect(Collectors.toSet());
        System.out.println(setnumbers);

    }
}

OUTPUT

List have duplicates
[10, 100, 15, 10, 1, 65, 55, 1]
Set doesn’t have duplicates
[1, 65, 100, 55, 10, 15]

You may also like...