Java ArrayList 添加具有相同 Id 的值

标签 java arraylist collections

所以我有一个数组列表,如下所示:<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/

相关文章:

java.lang.NullPointerException : Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)'

java - 如何在 Java 中将 PKCS#8 编码的 RSA key 转换为 PKCS#1?

java - 在 Java 中从文件中读取整数的最快方法是什么?

Java - 从多种不同类型中挑选一个 ArrayList

java - 多维 ArrayList 初始化

java - 如何使用 java Stream API 从 Map<Object,Integer> 收集数据到 List<Object>?

java - HTTPS Post 表单 Android

android - 我的 onReceive 响应哪个请求?

Java Stream 将列表中的元素映射为数字

java - 使用集合更新实体的 JPA 最佳实践