user11506663
user11506663

Reputation:

How can I edit a List which is set as a Value inside of a Map? (Specific example; Java)

Let's say I have a map like

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

Inside the List there are numbers {10,21,35,42,50}.

I would like to subtract each number with the following one e.g. 21-10, 35-21 and so on.

The end goal is for the List to have {11, 14, 7, 8}.

I'm having trouble with this because I don't know how to edit the List if it's set as a value.

Thanks in advance.

Upvotes: 0

Views: 1929

Answers (1)

Hei2
Hei2

Reputation: 44

The following code will do that:

public void someMethod() {
    Map<Integer, List<Integer>> map = new HashMap<>();
    // Fill the map with values.

    for (Integer key : map.keySet()) {
        map.put(key, generateNewList(map.get(key)));
    }
}

private List<Integer> generateNewList(List<Integer> inputList) {
    List<Integer> newList = new ArrayList<>(inputList.size()-1);
    for (int i = 1; i < inputList.size(); i++) {
        newList.add(inputList.get(i) - inputList.get(i-1));
    }
    return newList;
}

I should note: this will replace the list in the map with a new one containing the values you want, so it will not work if you need to keep the same lists.

Upvotes: 1

Related Questions