Trying to convert Java list to map

Asked 2 years ago, Updated 2 years ago, 27 views

I want to convert the list to map. As the result value is listed, {a=1,b=2}, {a=3,b=5} appears

Turning to the For door

For(int i=0; i<= list.size(); i++) { Map.put(a, list.get(i)) Map.put(b,list.get(i)) } If you type "for" in this way, you only get the value of the second list Result value {a=3,b=5}

a=1 b=2 a=3 b=5 How do I implement it to be this powerful?

java

2022-09-20 08:41

1 Answers

The map data type consists of a pair of key: value. Set key to a and value to 1 If you set "a" to 3, the value changes It is not added for 'a'.

To do so, why don't you put the list data type as value in the key value of 'a'?

// java code
length = 0
for(int i = 0; i < list.size(); i++) {
// It goes into the a,b key value at the same time, so in the list, 
// have a list value Let's assume ;; 
// [ [1,3], [2,5] , ...]
 // // a : [1,3]
    if(!map.containsKey('a') ) {
        List<Integer> nums = new ArrayList<Integer>();
        nums.add(list.get(i).get(0));
        map.put('a',  nums);
    }else{
        map.get('a').add(list.get(i).get(0));
    } 
// // b : [2,5]
    if(!map.containsKey('b') ) {
        List<Integer> nums = new ArrayList<Integer>();
        nums.add(list.get(i).get(1));
        map.put('b',  nums);
    }else{
        map.get('b').add(list.get(i).get(1));
    } 

    length += 1
}

for(int i = 0; i < length; i++) {
    System.out.println("a="+map.get('a').get(i)+" , "+ 
    "b="+map.get("b").get(i));
}
// Output result
// // a=1,b=2
// // a=3,b=5


2022-09-20 08:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.