lea*_*ovy 10 java lambda date java-8 java-stream
我有下面的值与哈希值映射,在值中我已经日期为字符串数据类型。我想比较地图中所有可用的日期,并仅提取一个具有最近日期的键值。
我想与值而不是键进行比较。
我已包含以下代码
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));
}
}
Run Code Online (Sandbox Code Playgroud)
预期的输出是:
关键4值2014-09-09
Entry<String, String> max = Collections.max(map.entrySet(), Map.Entry.comparingByValue());
Run Code Online (Sandbox Code Playgroud)
要么
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()));
}
});
Run Code Online (Sandbox Code Playgroud)
与其他日期相比,这应该提供最新(也称为最大)日期。
String max = map.values().stream().reduce("0000-00-00",
(a, b) -> b.compareTo(a) >= 0 ? b
: a);
Run Code Online (Sandbox Code Playgroud)
如果您还需要密钥,请执行此操作并返回 Map.Entry。需要 Java 9+
Entry<String, String> ent =
map.entrySet().stream().reduce(Map.entry("0", "0000-00-00"),
(a, b) -> b.getValue().compareTo(a.getValue()) >= 0 ? b
: a);
System.out.println(ent.getKey() + " -> " ent.getValue());
Run Code Online (Sandbox Code Playgroud)
这假设您的地图非空。如果为空,则返回 null。适用于 Java 8+
Entry<String, String> ent = map.entrySet().stream().reduce(
(a, b) -> b.getValue().compareTo(a.getValue()) >= 0 ? b
: a).orElseGet(() -> null);
Run Code Online (Sandbox Code Playgroud)