当前位置:   article > 正文

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);
  • 1
  • 2
示例代码
// 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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

image

2.Reduce

// reduce:接收一个BinaryOperator类型的函数式接口,将多个元素归并为一个
Optional<T> reduce(BinaryOperator<T> accumulator);
  • 1
  • 2
示例代码
// 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());
  • 1
  • 2
  • 3
  • 4

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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

image

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号