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
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.
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 ...
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With