定义
流是从支持数据处理操作的源生成的元素序列,源可以是数组、文件、集合、函数。流不是集合元素,它不是数据结构并不保存数据,它的主要目的在于计算,用完一次流就结束
生成
//通过集合生成
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream();
//通过数组生成
int[] intArr = new int[]{1, 2, 3, 4, 5};
IntStream stream = Arrays.stream(intArr);
//通过值生成
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
//通过文件生成
Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())
//通过函数生成
/*
iterate方法接受两个参数,第一个为初始化值,第二个为进行的函数操作,因为iterator生成的流为无限流,通过limit方法对流进行了截断,只生成5个偶数
*/
Stream<Integer> stream = Stream.iterate(0, n -> n + 2).limit(5);
/*generate方法接受一个参数,方法参数类型为Supplier,由它为流提供值。generate生成的流也是无限流,因此通过limit对流进行了截断*/
Stream<Double> stream = Stream.generate(Math::random).limit(5);
中间操作
map映射、distinct去重、filter过滤、sorted排序、group by 分组
//去重
List<Long> productIds = factoryProductsExportDtos.stream().distinct().map(FactoryProductsExportDto::getProductId).collect(Collectors.toList());
//对象数组
List<Product> productList = productReadService.findByIds(productIds);
//映射
List<Long> categoryIds = productList.stream().map(Product::getCategoryId).collect(Collectors.toList());
//过滤
List<ProductSupply> needProductSupplyList = productSupplyList.stream().filter(o -> o.getProductId().equals(product.getId()) && !(o.getFactoryId().equals(factoryId)))
.collect(Collectors.toList());
//排序
dishList.stream()
.filter(d -> d.getCalories() < 400) //筛选出卡路里小于400的菜肴
.sorted(comparing(Dish::getCalories)) //根据卡路里进行排序
.map(Dish::getName) //提取菜肴名称
.collect(Collectors.toList()); //转换为List
//分组 复杂集合
private static Map<Type, List<Dish>> afterJdk8(List<Dish> dishList) {
return dishList.stream().collect(groupingBy(Dish::getType));
}
limit限制返回个数,skip跳过流中的元素,flatMap转换流,match匹配
```java
//limit 返回前三个
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().limit(3);
//skip 跳过前两个
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().skip(2);
//flatMap 转换流
//[Hello, World, World]
//[Hello, World]
List<String> wordList = Arrays.asList("Hello", "World", "World");
List<String> strList = wordList.stream()
.map(w -> w.split(" "))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
//allMatch 全部元素满足
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().allMatch(i -> i > 3)) {
System.out.println("值都大于3");
}
//anyMatch匹配其中任意一个
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().anyMatch(i -> i > 3)) {
System.out.println("存在大于3的值");
}
//noneMatch 全部元素不满足
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().noneMatch(i -> i > 3)) {
System.out.println("值都小于3");
}
终端操作
List转Map
//所有工厂的id及名称
Map<Long, String> factoryMap = factoryService.getAll().stream().collect(Collectors.toMap(Factory::getId, Factory::getName));
//id为键 对象为值
Map<Long, CategoryVo> categoryDtoMap = categoryService.generateParent(categoryIds).stream().collect(Collectors.toMap(CategoryVo::getId, o -> o));
//根据产品id为键,对象为值
Map<Long,Product> productHashMap = productList.stream().collect(Collectors.toMap(Product::getId, Product -> Product));
统计元素个数、查找、求和、求极值
//通过count
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().count();
//通过counting
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().collect(counting());
//求和
/*reduce接受两个参数,一个初始值这里是0,一个BinaryOperator<T> accumulator来将两个元素结合起来产生一个新值*/
int sum = integerList.stream().reduce(0, (a, b) -> (a + b));
//引用方法里的值
int sum = integerList.stream().reduce(0, Integer::sum);
//获取极值
//min/max
Optional<Integer> min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional<Integer> max = menu.stream().map(Dish::getCalories).max(Integer::compareTo);
OptionalInt min = menu.stream().mapToInt(Dish::getCalories).min();
OptionalInt max = menu.stream().mapToInt(Dish::getCalories).max();
//minBy/minBy
Optional<Integer> min = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
Optional<Integer> max = menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));
//通过reduce获取最小最大值
Optional<Integer> min = menu.stream().map(Dish::getCalories).reduce(Integer::min);
Optional<Integer> max = menu.stream().map(Dish::getCalories).reduce(Integer::max);
总结
💡 Tips:对集合的操作便捷了很多,实际开发中,经常用到