进阶day07-Stream中的数据收集到集合
This commit is contained in:
32
javaSE-day07/src/com/inmind/stream03/Demo26.java
Normal file
32
javaSE-day07/src/com/inmind/stream03/Demo26.java
Normal file
@@ -0,0 +1,32 @@
|
||||
package com.inmind.stream03;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/*
|
||||
25.把Stream中的数据收集到集合
|
||||
Stream接口的一个方法collect
|
||||
R collect(Collector collector) 使用 Collector对此流的元素执行 mutable reduction操作。
|
||||
|
||||
Collector:表示收集者是一个接口。它的实现类对象,我们直接使用工具类获取
|
||||
Collectors:
|
||||
toList():List集合的收集者
|
||||
toSet():Set集合的收集者
|
||||
|
||||
|
||||
*/
|
||||
public class Demo26 {
|
||||
public static void main(String[] args) {
|
||||
//获取流
|
||||
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 5, 6, 6);
|
||||
//转为List集合(数据可以重复)
|
||||
List<Integer> list = stream.collect(Collectors.toList());
|
||||
System.out.println(list);
|
||||
//转为Set集合(数据不能重复)
|
||||
Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 5, 6, 6);
|
||||
Set<Integer> set = stream1.collect(Collectors.toSet());//Stream流重复
|
||||
System.out.println(set);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user