Collectors toSet() method in Java 8

Java 8ProgrammingObject Oriented Programming

The toSet() method of the Collectors class in Java returns a Collector that accumulates the input elements into a new Set.

The syntax is as follows

static <T> Collector<T,?,Set<T>> toSet()

Here, the parameter,

  • T - Type of the input elements.
  • Set - A collection that contains no duplicate elements.

To work with Collectors class in Java, import the following package

import java.util.stream.Collectors;

The following is an example to implement toSet() method in Java

Example

 Live Demo

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("This", "is", "it");
      Set<String> set = stream.collect(Collectors.toSet());
      System.out.println(set);
   }
}

Output

[This, is, it]
raja
Updated on 30-Jul-2019 22:30:25

Advertisements