Use Java8 stream to reduce Object to a Map

895 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER
    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);