How to reduce given list by using Lambda expression .reduce() method

前端 未结 2 585
梦谈多话
梦谈多话 2020-12-18 08:56
List integers = Arrays.asList(1, 2, 3, 5, 6, 8, 9, 10);
integers.stream().filter((integer) -> integer % 2 == 0).collect(Collectors.toList());
         


        
2条回答
  •  抹茶落季
    2020-12-18 09:37

    You can use the Stream.reduce(U identity, BiFunction accumulator, BinaryOperator combiner) method, which takes three parameters:

    • identity: The identity element is both the initial value of the reduction and the default result if there are no elements in the stream. In your case, it will be an empty list.
    • accumulator: The accumulator function takes two parameters: a partial result of the reduction and the next element of the stream (in this example, an integer). It applies a check for modulo 2 and then returns a new partial result.
    • combiner: It's purpose is to combine the internal temporary collector-accumulators of the stream batches that are being processes in parallel.

    For example:

    BinaryOperator> combiner = (x, y) -> { x.addAll(y); return x; };
    BiFunction, Integer, ArrayList> accumulator = (x, y) -> {
        if (y % 2 == 0) {
            x.add(y);
        }
        return x;
    };
    List list = Stream.of(1, 2, 3, 5, 6, 8, 9, 10).reduce(new ArrayList(),
                                                                   accumulator,
                                                                   combiner);
    System.out.println(list);
    

    Note that this solution may not work for parallel Streams. Also, it's way too easier to stick to the .filter() approach, so I strongly advice you to do so.

提交回复
热议问题