Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Java8 stream to reduce Object to a Map

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?

like image 260
user2272115 Avatar asked May 13 '26 00:05

user2272115


1 Answers

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!