Usage of function type congruent lambda expressions in Java 8

前端 未结 2 2028
既然无缘
既然无缘 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:02

    ArrayList::add actually has 2 parameters. The ArrayList object on which you call the add method and the parameter to add.

    ArrayList::add is equivalent to (list, element) -> list.add(element) and so it works as a BiConsumer

    0 讨论(0)
  • 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<String> asList = stringStream.collect(
        ArrayList::new,
        ArrayList::add,
        ArrayList::addAll
    );
    

    is equivalent to this:

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

    which will give the same result as this:

    List<String> asList = stringStream.collect(
        new Supplier<ArrayList<String>>() {
            @Override
            public ArrayList<String> get() {
                return new ArrayList<>();
            }
        },
    
        new BiConsumer<ArrayList<String>,String>() {
            @Override
            public void accept(ArrayList<String> list, String item) {
                list.add(item);
            }
        },
    
        new BiConsumer<ArrayList<String>,ArrayList<String>>() {
            @Override
            public void accept(ArrayList<String> list1, ArrayList<String> list2) {
                list1.addAll(list2);
            }
        }
    );
    
    0 讨论(0)
提交回复
热议问题