Group objects by multiple attributes using the Java 8 thread API

Given that we have a list of the Bank, each bank has several offices,

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

For instance:

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

Given the list of banks, I will have a bank representative card for each city. In the above example, I need the result

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

How can I achieve this result using the Java 8 API? Using pre-Java8 is simple, but verbose. Thank.

+4
source share
4 answers
Map<String, Set<Bank>> result = new HashMap<>();
for (Bank bank : banks) {
    for (String branch : bank.getBranches()) {
        result.computeIfAbsent(branch, b -> new HashSet<Bank>()).add(bank);
    }
}
+6
source
 banks.flatMap(bank -> bank.getBranches()
             .stream()
             .map(branch -> new AbstractMap.SimpleEntry<>(branch, bank)))
       .collect(Collectors.groupingBy(
             Entry::getKey, 
             Collectors.mapping(Entry::getValue, Collectors.toList())));

Result:

{London=[Mizuho, Goldman], NewYork=[Mizuho], Toronto=[Goldman]}
+4
source

, Stream.collect, , :

Map<String, List<Bank>> result = banks.stream()
    .collect(
        HashMap::new,
        (map, bank) -> bank.getBranches().forEach(branch ->
            map.computeIfAbsent(branch, k -> new ArrayList<>()).add(bank)),
        (map1, map2) -> map2.forEach((k, v) -> map1.merge(k, v, (l1, l2) -> {
            l1.addAll(l2);
            return l1;
        })));
+1

, , @JB Nizet, / . forEach

banks.forEach(b -> b.getBranches().forEach(ch -> result.computeIfAbsent(ch, k -> new ArrayList<>()).add(b)));

Stream AbacusUtil

Map<String, List<Bank>> res = Stream.of(banks)
          .flatMap(e -> Stream.of(e.getBranches()).map(b -> Pair.of(b, e)))
          .collect(Collectors.toMap2());
0

Source: https://habr.com/ru/post/1677884/


All Articles