gpt4 book ai didi

java - 如何在java中以多个日期作为值对 map 进行排序

转载 作者:行者123 更新时间:2023-12-02 10:27:58 26 4
gpt4 key购买 nike

如何按多个日期值对 HashMap 条目进行排序

假设我有一个 map ,其键为字符串,值为具有 2 个日期的对象。

按对象中的两个日期进行排序

Map<String, dateWrapper> map = new HashMap<>();
map.put("user10",new dateWrapper("20180131","20181231"));
map.put("user3",new dateWrapper("20170131","20171231"));
map.put("user5",new dateWrapper("20160131","20161231"));
map.put("user1",new dateWrapper("20170131","20170131"));

** 注意:以上字符串使用 SimpleDateFormat 解析为日期

预期输出为 user5,user1,user3,user10

公共(public)类 dateWrapper 实现可序列化{

private Date date1;
private Date date2;

}
List<Map.Entry<String, dateWrapper>> dateWrapperEntries = new ArrayList<>(map.entrySet());
Trying below this but its returning null
Collections.sort(dateWrapperEntries, Map.Entry.comparingByValue(Comparator.comparing(dateWrapper::getDate1).thenComparing(dateWrapper::getDate2)));

private static Date convertStringToDate(String inputStr) {
Date inputDate = null;
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd");

try {
inputDate = sdf.parse(inputStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputDate;
}

最佳答案

public static List<String> sort(Map<String, dateWrapper> map) {
// comparator to compare two dateWrapper from Map.Entry value
final Comparator<Map.Entry<String, dateWrapper>> comparator =
Comparator.comparing((Function<Map.Entry<String, dateWrapper>, Date>)e -> e.getValue().getDate1())
.thenComparing(e -> e.getValue().getDate2());

// convert map to entry set and compare it
return Optional.ofNullable(map).orElse(Collections.emptyMap()).entrySet().stream()
.sorted(comparator)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}

关于java - 如何在java中以多个日期作为值对 map 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53790837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com