Java8新特性之FlatMap&Reduce
2022/6/6 1:19:41
本文主要是介绍Java8新特性之FlatMap&Reduce,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.FlagMap
// flatMap:接收一个T返回一个R,将一个元素转为一个新的流 ;R apply(T t); <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
示例代码
// flatMap: 将一个元素转为一个新的流 1-N List<String> asList = Arrays.asList("zs", "ls", "ww", "zl", "tq"); List<String> stringList = asList.stream() .flatMap(item -> Arrays.asList(("1" + item).toUpperCase(), ("2" + item).toUpperCase(), ("3" + item).toUpperCase()).stream()) .collect(Collectors.toList()); System.out.println("stringList = " + stringList);
2.Reduce
// reduce:接收一个BinaryOperator类型的函数式接口,将多个元素归并为一个 Optional<T> reduce(BinaryOperator<T> accumulator);
示例代码
// reduce: 将多个元素归并为一个 N-1 List<Integer> asList = Arrays.asList(1, 2, 3, 4, 5); Optional<Integer> optional = asList.stream().reduce((x, y) -> x + y); System.out.println("optional.get() = " + optional.get());
3.Concat合并流
List<Qiu> list1 = Arrays.asList(new Qiu(1L, "AA"), new Qiu(2L, "BB"), new Qiu(3L, "CC")); List<Qiu> list2 = Arrays.asList(new Qiu(3L, "DD"), new Qiu(2L, "EE"), new Qiu(5L, "FF")); // Stream<Qiu> concat = Stream.concat(list1.stream(), list2.stream()); Map<Long, Qiu> map = new HashMap<>(); Stream.concat(list1.stream(), list2.stream()).forEach(item -> { Qiu qiu = item; if (map.containsKey(item.getId())) { qiu = map.get(item.getId()); qiu.setName(qiu.getName() + "---" + item.getName()); } map.put(item.getId(), qiu); }); System.out.println("map = " + map); List<Qiu> qiuList = map.values().stream().collect(Collectors.toList()); System.out.println("qiuList = " + qiuList);
这篇关于Java8新特性之FlatMap&Reduce的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南