How to find the latest date from the given map value in java

Use Collections.max with entrySet

Entry<String, String> max = Collections.max(map.entrySet(), Map.Entry.comparingByValue());

or

Entry<String, String> max = Collections.max(map.entrySet(),
    new Comparator<Entry<String, String>>() {
        @Override
        public int compare(Entry<String, String> e1, Entry<String, String> e2) {
            return LocalDate.parse(e1.getValue()).compareTo(LocalDate.parse(e2.getValue()));
        }
});

This should work

    Optional<Map.Entry<String, String>> result = map.entrySet().stream().max(Comparator.comparing(Map.Entry::getValue));
    System.out.println(result);

output is Optional[4=2014-09-09]


At the first glance, using String literals to represent Date is not a good approach and makes it more fragile and error prone. You would rather use LocalDate in the first place. However, with the assumption that you don't have any control over that data format (for instance, say, it is coming from another third party system), we can still devise an approach that solves the problem at hand. Here's how it looks.

Entry<String, String> maxEntry = map.entrySet().stream()
    .max(Comparator.comparing(e -> LocalDate.parse(e.getValue())))
    .orElseThrow(IllegalArgumentException::new);

The LocalDate.parse is used to convert the string representation of the date into a LocalDate which is a Comparable. That Comparable is then passed as a key to the Comparator construction method. And here's the output key-value pair upon the successful execution:

4=2014-09-09

If you can merely dispense with the String representation of date as suggested above, then you can make the above solution much more simpler and succinct.

Entry<String, LocalDate> maxEntry = map.entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .orElseThrow(IllegalArgumentException::new);