3

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 Answer 1

7
    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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.