假设我有一张地图,比如
Map<Integer, List<Integer>> map = new HashMap<>();在列表中有数字{10,21,35,42,50}。
我想用下面的数字减去每个数字,例如21-10,35-21等等。
最终目标是列表中包含{11,14,7,8}。
我在这方面遇到了问题,因为如果列表被设置为值,我不知道如何编辑它。
提前谢谢。
发布于 2019-05-16 12:05:29
下面的代码可以做到这一点:
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;
}我需要注意的是:这将用一个包含您想要的值的新列表替换map中的列表,因此如果您需要保留相同的列表,它将不起作用。
https://stackoverflow.com/questions/56158768
复制相似问题