how to get ArrayList<HashMap<String, String>> duplicate data

22 views Asked by At

How do I find duplicate key values ​​in the listMap contained in ArrayList<HashMap<String, String>>?

if the listMap is like below, the key DATA_ID =01 is duplicated. How do I extract only the duplicate data? ex. [{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}]

i'm trying to find duplicate data and calculate the corresponding values.

1

There are 1 answers

0
Malvin Lok On BEST ANSWER

You could use a new Map to do so, let's call it: 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); 
            }
        }
    }
}