[英]How to convert a list to a map with a set value in java 8
List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com"));
list.add(new Hosting(2, "aws.amazon.com"));
list.add(new Hosting(3, "digitalocean.com"));
list.add(new Hosting(2, "aws.amazon.com"));
我想將上面的列表轉換為Map<Integer, Set<String>>
1 -> {"liquidweb.com"}
2 -> {"aws.amazon.com"}
3 -> {"digitalocean.com"}
如何在Java 8中進行轉換?
使用toMap
:
Map<Integer, Set<String>> result = list.stream()
.collect(toMap(Hosting::getId,
e -> new HashSet<>(Collections.singleton(e.getValue())),
(l, r) -> {l.addAll(r); return l;}));
要么:
將groupingBy
與mapping
用作下游收集器:
Map<Integer, Set<String>> resultSet = list.stream()
.collect(groupingBy(Hosting::getId,
mapping(Hosting::getValue, toSet())));
就個人而言,我更喜歡后者,因為它更具可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.