使用 Java8 流将 Object 缩减为 Map
Use Java8 stream to reduce Object to a Map
如果我有一个class喜欢
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 还不是很熟悉。有什么建议吗?
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);
如果我有一个class喜欢
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 还不是很熟悉。有什么建议吗?
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);