如何在Java 8中将列表转换为具有设置值的地图

时间:2018-11-06 21:56:49

标签: java java-8 java-stream

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中进行转换?

1 个答案:

答案 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;}));

或:

使用groupingBymapping作为下游收集器:

Map<Integer, Set<String>> resultSet = list.stream()
          .collect(groupingBy(Hosting::getId, 
                       mapping(Hosting::getValue, toSet())));

我个人更喜欢后者,因为它更具可读性。