使用方法
/**
* 流的四种构建形式
*/
public class StreamConstructor {
/**
* 由数值直接构建流
*/
@Test
public void streamFromValue() {
Stream stream = Stream.of(1, 2, 3, 4, 5);
stream.forEach(System.out::println);
}
/**
* 通过数组构建流
*/
@Test
public void streamFromArray() {
int[] numbers = {1, 2, 3, 4, 5};
// 只能传一个int[] 类型的数组
IntStream stream = Arrays.stream(numbers);
stream.forEach(System.out::println);
}
/**
* 通过文件生成流
* @throws IOException
*/
@Test
public void streamFromFile() throws IOException {
// TODO 此处替换为本地文件的地址全路径
String filePath = "";
// 用此方法打印文件内容非常方便
Stream<String> stream = Files.lines(
Paths.get(filePath));
stream.forEach(System.out::println);
}
/**
* 通过函数生成流(无限流)
*/
@Test
public void streamFromFunction() {
// Stream stream = Stream.iterate(0, n -> n + 2);
Stream stream = Stream.generate(Math::random);
stream.limit(100)
.forEach(System.out::println);
}
}
概念区分:collect是方法,Collector是集合接口,Collectors是集合工具类
使用方法
/**
* 常见预定义收集器使用
*/
public class StreamCollector {
/**
* 集合收集器
*/
@Test
public void toList() {
List<Sku> list = CartService.getCartSkuList();
List<Sku> result = list.stream()
.filter(sku -> sku.getTotalPrice() > 100)
.collect(Collectors.toList());
System.out.println(
JSON.toJSONString(result, true));
}
/**
* 分组
*/
@Test
public void group() {
List<Sku> list = CartService.getCartSkuList();
// Map<分组条件,结果集合>
Map<Object, List<Sku>> group = list.stream()
.collect(
Collectors.groupingBy(
sku -> sku.getSkuCategory()));
System.out.println(
JSON.toJSONString(group, true));
}
/**
* 分区 根据判断条件返回两个分区,一个是结果为true的,另一个是结果为false的
*/
@Test
public void partition() {
List<Sku> list = CartService.getCartSkuList();
Map<Boolean, List<Sku>> partition = list.stream()
.collect(Collectors.partitioningBy(
sku -> sku.getTotalPrice() > 100));
System.out.println(
JSON.toJSONString(partition, true));
}
}
原文:https://www.cnblogs.com/hongzuiliyu/p/14249338.html