Arsha
Arsha

Reputation: 125

Converting list of objects to key value pair in java

I have java list of objects [["X","10"],["y","20"],["Z","30"]]

How do I convert this to key value pair? I want it to be

key:value X:10 y:20 Z:30

Thanks

Upvotes: 2

Views: 4996

Answers (2)

Lal Mohandas
Lal Mohandas

Reputation: 116

You can use 'java.util.stream.Collectors' for this. Please refer to the below example

    public class KeyValue {

            private String key;
            private int value;

            public KeyValue (String key, int value) {
                this.key = key;
                this.value = value;
            }

            public String getKey() {
                return key;
            }

            public int getValue() {
                return value;
            }
    }

To convert List to Map

    List <KeyValue> list = new ArrayList<>();

    list.add(new KeyValue("X", 10));
    list.add(new KeyValue("Y", 20));
    list.add(new KeyValue("Z", 30));


    Map<String, Integer> map = list.stream().collect(
            Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue()));

Upvotes: 3

404pio
404pio

Reputation: 1032

dict( [["X","10"],["y","20"],["Z","30"]])

Upvotes: 0

Related Questions