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中进行转换?
答案 0 :(得分:4)
使用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())));
我个人更喜欢后者,因为它更具可读性。