Custom collecting via collect()

In the case of an IDENTITY_FINISH collection operation, there is at least one more solution for obtaining a custom collector. This solution is facilitated by the following method:

<R> R collect​(Supplier<R> supplier, BiConsumer<R,​? super T> accumulator, BiConsumer<R,​R> combiner)

This flavor of collect() is a great fit as long as we deal with an IDENTITY_FINISH collection operation and we can provide a supplier, accumulator, and combiner.

Let's take a look at some examples:

List<String> numbersList = Stream.of("One", "Two", "Three")
.collect(ArrayList::new, ArrayList::add,
ArrayList::addAll);

Deque<String> numbersDeque = Stream.of("One", "Two", "Three")
.collect(ArrayDeque::new, ArrayDeque::add,
ArrayDeque::addAll);

String numbersString = Stream.of("One", "Two", "Three")
.collect(StringBuilder::new, StringBuilder::append,
StringBuilder::append).toString();

You can use these examples to identify more JDK classes whose signatures are well-suited for use with method references as arguments to collect().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset