Usage of function type congruent lambda expressions in Java 8

前端 未结 2 2026
既然无缘
既然无缘 2021-02-07 22:21

I struggle with the definition and usage of the

Stream.collect(Supplier supplier, BiConsumer accumulator, BiConsumer comb         


        
2条回答
  •  无人共我
    2021-02-07 23:07

    The accumulator BiConsumer's two parameters are (1) the list itself and (2) the item to add to it. This:

    List asList = stringStream.collect(
        ArrayList::new,
        ArrayList::add,
        ArrayList::addAll
    );
    

    is equivalent to this:

    List asList = stringStream.collect(
        () -> new ArrayList<>(),
        (list, item) -> list.add(item),
        (list1, list2) -> list1.addAll(list2)
    );
    

    which will give the same result as this:

    List asList = stringStream.collect(
        new Supplier>() {
            @Override
            public ArrayList get() {
                return new ArrayList<>();
            }
        },
    
        new BiConsumer,String>() {
            @Override
            public void accept(ArrayList list, String item) {
                list.add(item);
            }
        },
    
        new BiConsumer,ArrayList>() {
            @Override
            public void accept(ArrayList list1, ArrayList list2) {
                list1.addAll(list2);
            }
        }
    );
    

提交回复
热议问题