如何获取ArrayList<HashMap<String, String>>重复数据

问题描述 投票:0回答:1

如何在ArrayList包含的listMap中找到重复的键值>?

如果listMap如下所示,则键DATA_ID =01是重复的。如何仅提取重复数据? 前任。 [{TIMESTAMP=2024-03-28 00:00:27.925321,DATA_ID=01,VALUE=-273.15,INFO_SEQ=24668992},{TIMESTAMP=2024-03-28 00:01:30.925321,DATA_ID=01,VALUE=- 275.15,NFO_SEQ=24668992},{TIMESTAMP=2024-03-28 00:01:31.452321,DATA_ID=02,VALUE=-275.15,NFO_SEQ=24668992}]

我正在尝试查找重复数据并计算相应的值。

arraylist
1个回答
0
投票

您可以使用新的地图来执行此操作,我们称之为:

dataIdMap

import java.util.*;

public class Main {
    public static void main(String[] args) {
        ArrayList<HashMap<String, String>> listMap = new ArrayList<>();
        // Add your data to listMap here...
        // listMap.add(xxxx, xxx)
        
        // Setup new map
        HashMap<String, List<HashMap<String, String>>> dataIdMap = new HashMap<>();
        
        for(HashMap<String, String> item : listMap) {
            String dataId = item.get("DATA_ID");

            if(!dataIdMap.containsKey(dataId)) {
                dataIdMap.put(dataId, new ArrayList<HashMap<String, String>>());
            }

            dataIdMap.get(dataId).add(item);
        }
        
        // Loop through and find duplicates
        for(Map.Entry<String, List<HashMap<String, String>>> entry : dataIdMap.entrySet()){
            if (entry.getValue().size() > 1) {
                // This is duplicate entry, you can calculate value here.
                System.out.println("Duplicate DATA_ID: " + entry.getKey()); 

                // If you want to calculate values (let's add them together), do the following:
                double totalValue = 0.0;
                for (HashMap<String, String> map : entry.getValue()) {
                    totalValue += Double.parseDouble(map.get("VALUE"));
                }
                System.out.println("Total Value for this duplicate ID: " + totalValue); 
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.