Search code examples
javadatearraylisthashmapdate-comparison

Compare two arraylists to return the latest date


I have two arraylists as follows.

ArrayList<String> keys = new ArrayList<>();
ArrayList<String> values = new ArrayList<>();
keys.add("1","1","1","2","2","3");
values.add("2016-06-22 07:18:45", "2016-06-22 08:18:45", "2016-06-22 09:18:45",
"2016-06-22 03:18:45","2016-06-22 04:18:45","2016-06-22 01:18:45");

Now i need the function

HashMap latestValues(keys, values); The output should be as follows,

["1"=>"2016-06-22 09:18:45","2"=>"2016-06-22 04:18:45", "3"=>"2016-06-22 01:18:45"]

Returning the latest dated single value for that particular key. Can anyone please suggest how to achieve this.

Thanks and advance!


Solution

  • I think this will do it.

    public static void main(String[] args) {
        ArrayList<String> keys = new ArrayList<>(Arrays.asList("1", "1", "1", "2", "2", "3"));
        ArrayList<String> values = new ArrayList<>(Arrays.asList("2016-06-22 07:18:45", "2016-06-22 08:18:45", "2016-06-22 09:18:45",
                "2016-06-22 03:18:45", "2016-06-22 04:18:45", "2016-06-22 01:18:45"));
        HashMap<String, String> map = new HashMap<String, String>();
    
        for (int i = 0; keys.size() == values.size() && i < keys.size(); i++) {
            String key = keys.get(i);
            String value = values.get(i);
            if (!map.containsKey(key) || dateAsNo(value) > dateAsNo(map.get(key))) {
                map.put(key, value);
            }
        }
        System.out.println(map);
    }
    
    public static long dateAsNo(String v) {
        return Long.parseLong(v.replaceAll("\\D", ""));
    }
    

    It will only work if all the dates have the same format yyyy-MM-dd hh:mm:ss