Daily tip #18
Tip of the day #18
Use the groupingBy collector to create a Map<?, List<?>> from a List<?>
.
What is it?
The groupingBy collector is a static method in the Collectors class that returns a Collector implementing a “group by” operation on input elements of type T, grouping elements according to a classification function, and returning the results in a Map.
Let’s see how it works:
Imagine that you have an Account class:
class Account {
UUID id,
Card card
}
class Card {
UUID id,
String number,
String flag
}
Then you can group by card.getFlag() ( master, visa, others).
Map<String, List<Account>> accountMap =
accountList.stream().collect(Collectors.groupingBy(account -> account.getCard().getFlag()));
Easy right?
How to
Take a look in repo-tip-18 to see a real example of today’s tip.