If I have a class like
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
}
and I have a Set<Property> properties of a few properties that I would like to reduce into a Map of just the key and values from these Property objects.
Most of my solutions ended up being not so suave. I know there's a handy way to do these with a Collector but I'm not that familiar with Java8 yet. Any tips?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With