加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

使用Java8流将Object减少为Map

发布时间:2020-12-15 04:28:12 所属栏目:Java 来源:网络整理
导读:如果我有类似的课程 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} 我有一
如果我有类似的课程

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>我希望将一些属性的属性简化为只有这些Property对象中的键和值的Map.

我的大多数解决方案最终都不那么温文尔雅.我知道有一个方便的方法与收集器一起做这些,但我还不熟悉Java8.有小费吗?

解决方法

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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读