-1

I was wondering how to properly (or even if you can) add data to a HashMap like an ArrayList?

So I have a function, which checks the entered string for commas and separates the values, adds them into an ArrayList and then stores the ArrayList keyed against the name of the field they were entering data to:

ArrayList<String> dataList = new ArrayList<>();
Map<String, ArrayList<String>> dataMap = new HashMap<String, ArrayList<String>>();
String[] parts;
public void CheckForMultipleEntries(String field, String data){
    dataList.clear();
    if(data.contains(",")){
        data.replace("", "");
        parts = data.split(",");
        for(String part : parts){
            dataList.add(part);
        }
        dataMap.put(field, dataList);
    }

    System.out.println(dataMap);
    System.out.println(dataMap.get("test"));
}

However say first for "Header" I enter "test1, test2, test3" - this will enter & output correctly (as: {Header=[test1, test2, test3]}) but if for the next value I then enter, say, "Body" "test4, test5, test6" then when I output the map I get {Header=[test4, test5, test6], Body=[test4, test5, test6]}.

Why is it overwriting the values, but not the keys? And how do I fix it?

Thanks for any help!

Hülya
  • 3,353
  • 2
  • 12
  • 19

2 Answers2

2

The Value is getting overidden because, you are using

dataList.clear();

you are putting the reference of arraylist dataList in the hashmap. so you have to re initialize the arraylist evertime you allot with new values

replacing dataList.clear(); with dataList=new ArrayList<>(); will solve your issue

0

Smth. like that. Do not forget, that each map key have it's own List:

public static void add(Map<String, List<String>> map, String key, String value) {
    map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35