鉴于我们有一个银行列表,每个银行都有多个办事处,
public class Bank {
private String name;
private List<String> branches;
public String getName(){
return name;
}
public List<String> getBranches(){
return branches;
}
}例如:
Bank "Mizuho": branches=["London", "New York"]
Bank "Goldman": branches = ["London", "Toronto"]给定一个银行列表,我将拥有每个城市的银行代表图。在上面的示例中,我需要
Map["London"] == ["Mizuho", "Goldman"]
Map["New York"] == ["Mizuho"]
Map["Toronto"] == ["Goldman"]如何使用Java 8 API实现该结果?使用Java8之前的版本很简单,但很繁琐。谢谢你。
发布于 2017-05-25 19:52:24
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);
}
}发布于 2017-05-25 20:26:19
banks.flatMap(bank -> bank.getBranches()
.stream()
.map(branch -> new AbstractMap.SimpleEntry<>(branch, bank)))
.collect(Collectors.groupingBy(
Entry::getKey,
Collectors.mapping(Entry::getValue, Collectors.toList())));结果将是:
{London=[Mizuho, Goldman], NewYork=[Mizuho], Toronto=[Goldman]}发布于 2017-05-26 03:16:06
您可以使用接受供应商、累加器函数和组合器函数的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;
})));https://stackoverflow.com/questions/44171555
复制相似问题