Java教程

Java8新特性之FlatMap&Reduce

本文主要是介绍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);

image

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());

image

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);

image

这篇关于Java8新特性之FlatMap&Reduce的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!