Use Java8 stream to shrink object to 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 Set<Property> properties

several properties that I would like to reduce to Map

just the key and values ​​from these objects Property

.

Most of my decisions weren't very stubborn. I know there is a convenient way to do this using Collector

, but I'm not familiar with Java8 yet. Any advice?

+3


source to share


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

      



+7


source







All Articles