Mainak Sethi
Mainak Sethi

Reputation: 31

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?

Upvotes: 3

Views: 8190

Answers (6)

Shubhang Malviya
Shubhang Malviya

Reputation: 1635

While you pass objects in java you pass actually the reference of that object and all the items you add point to the same list object as JB Nizet explained in his answer . Following are the things you can do :

  1. Create a new list each time an add it to the Hashmap object.
  2. Use Google Guava Collections like :

     Multimap<String, String> multiMap = ArrayListMultimap.create();
    
     // put values into map for segment
    
     multiMap.put("segment", "1");
     multiMap.put("segment", "100");
    
     // put values into map for subDepartment
    
     multiMap.put("subDepartment", "2");
     multiMap.put("subDepartment", "200");
    
     // put values into map for officerTitle
    
     multiMap.put("officerTitle", "3");
     multiMap.put("officerTitle", "300");
    
  3. Or Use Apache Commons Collection like :

     // create multimap to store key and values
    
     MultiMap multiMap = new MultiValueMap();
    
     // put values into map for segment
    
     multiMap.put("segment", "1");
     multiMap.put("segment", "100");
    
     // put values into map for subDepartment
    
     multiMap.put("subDepartment", "2");
     multiMap.put("subDepartment", "200");
    
     // put values into map for officerTitle
    
     multiMap.put("officerTitle", "3");
     multiMap.put("officerTitle", "300");
    

All will give you correct output. !

Upvotes: 2

learner
learner

Reputation: 365

you can make every time new list and and and add value value to it and then you put in the map.

like this..

Map < String, List< String>> map = new HashMap< String, List< String>>();

    // create list one and store values
    List<String> valSetOne = new ArrayList<String>();
    valSetOne.add("1");
    //valSetOne.add("Aeroplane");

    // create list two and store values
    List<String> valSetTwo = new ArrayList<String>();
    valSetTwo.add("2");
   // valSetTwo.add("Banana");

    // create list three and store values
    List<String> valSetThree = new ArrayList<String>();
    valSetThree.add("3");
    //valSetThree.add("Car");

    // put values into map
    map.put("A", valSetOne);
    map.put("B", valSetTwo);
    map.put("C", valSetThree);


    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        String key = entry.getKey();
        List<String> values = entry.getValue();
        System.out.println("Key = " + key);
        System.out.println("Values = " + values );
    }
}

Upvotes: 1

ravikumar
ravikumar

Reputation: 893

You need to create a list before putting in HashMap,

   public static void main(String trav[]){
        final Map<String, List<String>> paramMap = new HashMap<>();
        paramMap.put("segment", Lists.newArrayList("1"));
        paramMap.put("subDepartment", Lists.newArrayList("2"));
        paramMap.put("officerTitle", Lists.newArrayList("3"));
        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);
            }
    }

Upvotes: 2

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

That is because you are referencing only one instance of List object to the HashMap.

When the reference to the List change the Values of the HashMap changes.

In your situation

    list1.add("1");
    paramMap.put("segment", list1);
    list1.clear();
    list1.add("2");
    paramMap.put("subDepartment", list1);
    list1.clear();
    list1.add("3");

That last value you added to the list after you clear it will be the values of all the data in your HashMap

solution:

Create a new instance of List every time you add to the HashMap

Upvotes: 1

newbieee
newbieee

Reputation: 450

You have to create a new list each time when you want to put in a map. It's because map is checking the reference of the list and you're inserting the list with same reference and map won't store duplicate keys so basically it updates the entry with the last given list value.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692231

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.

Upvotes: 2

Related Questions