我的 HashMap 具有以下值,这些值是我将日期作为字符串数据类型的值。我想比较 map 中可用的所有日期,并仅提取一个具有最近日期的键值。
我想与值而不是键进行比较。
我已经添加了下面的代码
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));
}
}
这个的预期输出是:
关键 4 个值 2014-09-09
最佳答案
Entry<String, String> max = Collections.max(map.entrySet(), Map.Entry.comparingByValue());
或
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()));
}
});
关于java - 如何从java中给定的 map 值查找最新日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58279079/