所以我有一个数组列表,如下所示:<id,value,id,value,...>
我应该找到所有具有相同 id 的元素,并将相关值加在一起到结果数组列表中(值总是在 id 之后)。起初我认为这个问题很简单,然后继续尝试:
List<String> resultList = new ArrayList<>();
for(int i = 0; i < myList.size(); i+=2){
BigInteger currentID = new BigInteger(myList.get(i));
BigInteger currentSum = new BigInteger(myList.get(i+1));
String currentId = myList.get(i);
int j = 2;
while(j < myList.size()){
if(currentId.equals(myList.get(j))){
BigInteger value2 = new BigInteger(myList.get(j+1));
currentSum = currentID.add(value2);
}
resultList.add(currentId);
resultList.add(String.valueOf(currentSum));
j+=2;
}
}
不用说这是不正确的,许多问题之一是已经加在一起的值将被重新添加到结果数组中,所以我认为它们应该以某种方式在循环中被删除。你们对如何解决这个问题有什么建议吗?
最佳答案
假设您可以使用 map :
我最初认为它使用 Map<String, String> map = new HashMap();
Pseudo code:
For each (id,value pair) in resultList
if map.get(id) exists
add the value to the existing entry in the map
else
add a new entry in the map for (id,value)
作为代码(注意:未经测试,可能无法编译,不会直接复制和粘贴):
Map<String, String> map = new HashMap<>();
for(int i = 0; i < myList.size(); i+=2){
String listId = resultList.get(i); //get the Id from the resultList
String listValue = resultList.get(i+1) //get the value from the resultList
if(map.get(listId) != null) { // if the map has this Id
map.put(listId, map.get(listId)+ listValue); // add the Id's list value
}
else { // if the map doesn't have this Id
map.put(listId, listValue) // add the entry to the map
}
}
然后您可以获取结果 map
并转换回列表。
我将让您编写代码以获取 map 中的每个条目并将其添加到新列表中。谷歌在这里可以提供帮助。
关于Java ArrayList 添加具有相同 Id 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59364964/