Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm having hash map with below values, in values I've date as string data type. I would like to compare all the dates which is available in map and extract only one key-value which has a very recent date.

I would like to compare with values not keys.

I've included the code below

import java.util.HashMap;
import java.util.Map;

public class Test {

  public static void main(String[] args) {

      Map<String, String> map = new HashMap<>();
      map.put("1", "1999-01-01");
      map.put("2", "2013-10-11");
      map.put("3", "2011-02-20");
      map.put("4", "2014-09-09");

      map.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));
    }

}

The expected output for this one is:

Key 4 Value 2014-09-09

like image 824
learn groovy Avatar asked Oct 08 '19 01:10

learn groovy


People also ask

Can we update value in map?

The Combination of containsKey and put Methods. The combination of containsKey and put methods is another way to update the value of a key in HashMap. This option checks if the map already contains a key. In such a case, we can update the value using the put method.

Can we update map while iterating?

Well, you can't do it by iterating over the set of values in the Map (as you are doing now), because if you do that then you have no reference to the keys, and if you have no reference to the keys, then you can't update the entries in the map, because you have no way of finding out which key was associated with the ...

How do you check if a value is present in a map in Java?

HashMap containsValue() Method in Java HashMap. containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map.


2 Answers

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()));
        }
});
like image 163
bathudaide Avatar answered Sep 16 '22 17:09

bathudaide


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]

like image 24
Rajkumar Natarajan Avatar answered Sep 19 '22 17:09

Rajkumar Natarajan