【问题标题】:Use Java8 stream to reduce Object to a Map使用 Java8 流将 Object 缩减为 Map
【发布时间】:2015-06-12 22:59:51
【问题描述】:

如果我有类似的课程

public class Property {
    private String id;
    private String key;
    private String value;

    public Property(String id, String key, String value) {
        this.id = id;
        this.key = key;
        this.value = value;
    }
    //getters and setters
}

我有几个属性的Set<Property> properties,我想将这些属性简化为Map,这些属性仅包含来自这些Property 对象的键和值。

我的大多数解决方案最终都不是那么温和。我知道使用Collector 可以很方便地完成这些操作,但我对Java8 还不是很熟悉。有什么建议吗?

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:
        Set<Property> properties = new HashSet<>();
        properties.add(new Property("0", "a", "A"));
        properties.add(new Property("1", "b", "B"));
        Map<String, String> result = properties.stream()
            .collect(Collectors.toMap(p -> p.key, p -> p.value));
        System.out.println(result);
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 2022-01-17
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      相关资源
      最近更新 更多