Close

Java 8 Streams - Collectors.toSet Examples

Java 8 Streams Java Java API 


java.lang.Objectjava.lang.Objectjava.util.stream.Collectorsjava.util.stream.CollectorsLogicBig

The static method, Collectors.toSet() returns a Collector which produces a new Set instance, populated with stream elements if used as parameter of Stream.collect(Collector) method.

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


Examples


package com.logicbig.example.collectors;

import java.math.BigDecimal;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ToSetExample {
public static void main (String[] args) {
Stream<BigDecimal> s = Stream.iterate(
BigDecimal.ONE, bigDecimal ->
bigDecimal.add(BigDecimal.ONE))
.limit(10)
.peek(System.out::println);

Set<BigDecimal> l = s.collect(Collectors.toSet());
System.out.println(l);
}
}

Output

1
2
3
4
5
6
7
8
9
10
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Original Post




See Also