Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a java hashmap containing list?

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import mainak.faisal;
import mainak.pulkit;

public class StartingPoint {

    public static void main( String trav[] ) {
        final Map<String, List<String>> paramMap = new HashMap<>();
        List<String> list1 = new ArrayList<String>();
        list1.add("1");
        paramMap.put("segment", list1);
        list1.clear();
        list1.add("2");
        paramMap.put("subDepartment", list1);
        list1.clear();
        list1.add("3");
        paramMap.put("officerTitle", list1);

        for( Map.Entry<String, List<String>> entry : paramMap.entrySet() ) {
            String key = entry.getKey();
            System.out.println("ACTIONKEY"+"------"+key);

            for (String value : entry.getValue()) {
                System.out.println("ACTIONVALUE-----"+value);
            }
        }
    }
}

Expected Output:

ACTIONKEY------segment
ACTIONVALUE-----1
ACTIONKEY------subDepartment
ACTIONVALUE-----2
ACTIONKEY------officerTitle
ACTIONVALUE-----3

But its showing :

ACTIONKEY------segment
ACTIONVALUE-----3
ACTIONKEY------subDepartment
ACTIONVALUE-----3
ACTIONKEY------officerTitle
ACTIONVALUE-----3

Why this is happening? How can I achieve the desired result without making different lists?

like image 998
Mainak Sethi Avatar asked Mar 26 '26 14:03

Mainak Sethi


1 Answers

If you want 3 different lists in your map, then you need to create 3 lists. Creating only one list will cause the map to contain 3 references to the same list, containing what you stored in the list at the last step:

segment ---------
                 \
subDepartment----  [3]
                 /
officerTitle ----

What you want is

segment --------- [1]

subDepartment---- [2]

officerTitle ---- [3]

So you need 3 different lists. Understand that putting a list in a map doesn't create a copy of the list. It only stores a reference (a pointer, if you prefer) to the list passed as argument.

like image 185
JB Nizet Avatar answered Mar 29 '26 03:03

JB Nizet