32 lines
991 B
Java
32 lines
991 B
Java
package com.inmind.stream07;
|
|
|
|
import java.util.List;
|
|
import java.util.Set;
|
|
import java.util.stream.Collectors;
|
|
import java.util.stream.Stream;
|
|
|
|
/*
|
|
把Stream中的数据收集到集合
|
|
Stream接口的一个方法collect
|
|
R collect(Collector collector) 使用 Collector对此流的元素执行 mutable reduction操作。
|
|
|
|
Collector:表示收集者是一个接口。它的实现类对象,我们直接使用工具类获取
|
|
Collectors:
|
|
toList():List集合的收集者
|
|
toSet():Set集合的收集者
|
|
|
|
|
|
*/
|
|
public class Demo22 {
|
|
public static void main(String[] args) {
|
|
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5,5,5);
|
|
//收集到List集合
|
|
List<Integer> list = stream.collect(Collectors.toList());
|
|
System.out.println(list);
|
|
//收集到Set集合
|
|
Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 4, 5);
|
|
Set<Integer> set = stream1.collect(Collectors.toSet());
|
|
System.out.println(set);
|
|
}
|
|
}
|