Separating elements via Collectors.partitioningBy()

Sometimes, we don't want to delete the elements that don't match our predicate. What we actually want is to separate elements based on our predicate. Well, this is achievable via Collectors.partitioningBy(Predicate p).

Basically, Collectors.partitioningBy() will separate the elements into two lists. These two lists are added to a Map as values. The two keys of this Map will be true and false:

Map<Boolean, List<Melon>> separatedMelons = melons.stream()
.collect(Collectors.partitioningBy(
(Melon t) -> t.getWeight() >= 3000));

List<Melon> weightLessThan3000 = separatedMelons.get(false);
List<Melon> weightGreaterThan3000 = separatedMelons.get(true);

So, the true key is for retrieving the List that contains the elements that match the predicate, while the false key is for retrieving the List that contains the elements that didn't match the predicate.

By way of a bonus, if we want to check whether all the elements of a List are the same, then we can rely on Collections.frequency(Collection c, Object obj). This method returns the number of elements in the specified collection equal to the specified object:

boolean allTheSame = Collections.frequency(
melons, melons.get(0)) == melons.size());

If allTheSame is true, then all elements are the same. Note that equals() and hashCode() of the object from the List must be implemented accordingly.

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

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