mapping()

User problem: For each type of melon, I want the list of weights in ascending order.

By using mapping​(Function<? super T,​? extends U> mapper, Collector<? super U,​A,​R> downstream), we can apply a mapping function to each element of the current collector and accumulate the output in the downstream collector.

For example, for grouping the weights of melons by type, we can write the following snippet of code:

Map<String, TreeSet<Integer>> melonsMapping = melons.stream()
.collect(groupingBy(Melon::getType,
mapping(Melon::getWeight, toCollection(TreeSet::new))));

The output will be as follows:

{Crenshaw=[1700, 2000], Gac=[3000], Hemi=[1600, 2000, 2600]}

User problem: I want two lists. One should contain the melon types lighter than (or equal to) 2,000 g and the other one should contain the rest of the types.

Partitioning melons that are heavier than 2,000 g and collecting only their types can be done as follows:

Map<Boolean, Set<String>> melonsMapping = melons.stream()
.collect(partitioningBy(m -> m.getWeight() > 2000,
mapping(Melon::getType, toSet())));

The output is as follows:

{false=[Crenshaw, Hemi], true=[Gac, Hemi]}
..................Content has been hidden....................

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