[英]Use Java8 stream to reduce Object to a Map
如果我有类似的课程
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
,我想将这些Property
简化为只有这些Property
对象中的键和值的Map
。
我的大多数解决方案最终都不那么温文尔雅。 我知道有一个方便的方法与Collector
一起做这些,但我还不熟悉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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.