Group objects by multiple attributes with Java 8 stream API

Viewed 1642

Given we have a list of Bank, each Bank have multiple offices,

public class Bank {
   private String name;
   private List<String> branches;
   public String getName(){
       return name;
   }
   public List<String> getBranches(){
       return branches;
   }
}

For example:

Bank "Mizuho": branches=["London", "New York"]
Bank "Goldman": branches = ["London", "Toronto"]

Given a list of banks, I would have a map of bank representation for each city. In the example above, I need a result of

Map["London"] == ["Mizuho", "Goldman"]
Map["New York"] == ["Mizuho"]
Map["Toronto"] == ["Goldman"]

How can I achieve that result using Java 8 API? Using pre-Java8 is easy, but verbose. Thank you.

4 Answers
Related