user3383301
user3383301

Reputation: 1911

Filter ArrayList of HashMap based on date values

Need to filter duplicates values by id keeping the record with latest timestamp.

Below is the code:

HashMap<String, Object> sampleMap = new HashMap<String, Object>();      
sampleMap.put("Name", "Ronaldo");
sampleMap.put("Playerid", "11");
sampleMap.put("Date", "2020-05-01T08:35:42-04:00");

HashMap<String, Object> sampleMap1 = new HashMap<String, Object>();     
sampleMap1.put("Name", "Messi");
sampleMap1.put("Playerid", "12");
sampleMap1.put("Date", "2020-06-01T08:35:42-04:00");

HashMap<String, Object> sampleMap2 = new HashMap<String, Object>();     
sampleMap2.put("Name", "Messi");
sampleMap2.put("Playerid", "12");
sampleMap2.put("Date", "2020-05-01T08:35:42-04:00");

ArrayList<HashMap<String, Object>> fMap = new ArrayList<HashMap<String, Object>>();

fMap.add(sampleMap);
fMap.add(sampleMap1);
fMap.add(sampleMap2);

Expected Result :

fmap[sampleMap, sampleMap1]

Final Output should have only sampleMap, sampleMap1 because sampleMap1 and sampleMap2 have same playerId but date for sampleMap1 is latest hence it should be there not sampleMap2.

Couldn't find logic to solve this case. Please help me out

Upvotes: 1

Views: 1177

Answers (1)

Roman Yushchenko
Roman Yushchenko

Reputation: 54

If you want to sort a list of maps. You could use the functions of Java 8, namely Stream API. The comparator often uses for sort. You could choose which fields you want to sort by Comparator.comparing(map ->map.get("field")). To remove duplicate value the Stream API represents the distinct() function.

Your list of players could be sorted like this:

    fMap.stream()
        .sorted(Comparator.comparing(map -> Integer.parseInt((String)map.get("Playerid")))
                          .thenComparing(map -> LocalDate.parse((String)map.get("Date"), 
                                                                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.ENGLISH))))
        .distinct()
        .collect(Collectors.toList());

Upvotes: 1

Related Questions