Java8 lambda+流使用

本文深入探讨了Java 8的流(Stream)API,包括如何从不同数据源生成流,如数组、集合和文件。讲解了中间操作如map、filter、distinct、sorted和groupingBy等,以及终端操作如count、find、reduce和collect的使用。通过实例展示了流的limit、skip和flatMap等方法,同时涵盖了allMatch、anyMatch和noneMatch等匹配操作。最后,总结了流在实际开发中的便利性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义

流是从支持数据处理操作的源生成的元素序列,源可以是数组、文件、集合、函数。流不是集合元素,它不是数据结构并不保存数据,它的主要目的在于计算,用完一次流就结束

生成

//通过集合生成
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:对集合的操作便捷了很多,实际开发中,经常用到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值