0

I have a Map that looks like this:

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

Lets say the contents of the map looks like this:

one, [-55, -55, -54, -54, -55, -54, -54, -54, -54, -55]
two, [-61, -61, -61, -61, -60, -61, -60, -61, -60, -60]
three, [-69, -69, -68, -68, -68, -69, -70, -68, -69, -69]

I have created a method called "addRandomValuesToList" that looks at a list of integers called input, takes 4 values and puts them into another list called randomValues.

public static List<Integer> addRandomValuesToList(List<Integer> input) 
{
    List<Integer> randomValues = new ArrayList<>();
    ...
    return randomValues 
}

I want to use the addRandomValuesToList method on all the list I have in the map so I get for example:

one, [-54, -54, -54, -54]
two, [-61, -61, -61, -61,]
three, [-69 -69, -70, -68]

I have a hard time doing this. I tried something like:

Map<String, List<Integer>> test = new TreeMap<>();

for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
     newList = addRandomValuesToList(entry.getValue());
     test.put(entry.getKey(), newList);
}

This causes some lists in the test map to be completely empty. Am I doing something wrong or is my approach wrong?

JDoe
  • 221
  • 4
  • 14

1 Answers1

1

One should declare the variable as local as possible. (It will store memory only once in a loop.)

Also the Map.Entry is backed by the internal data of the map. So it has a method setValue, though ofcourse not setKey.

Map<String, List<Integer>> test = new TreeMap<>();
for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
     List<Integer> newList = addRandomValuesToList(entry.getValue());
     entry.setValue(newList);
}

Also the getValue list is internal data from the map, is backed by the map. One could do:

entry.getValue().add(42);

addRandomValuesToList: if it indeed modifies the passed entry value, the method can be void, no need to do something with the result.

About the error I am uncertain. Every list in the map, must be a new instance (new ArrayList<>() or such).

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138