gpt4 book ai didi

java - 使用 TreeMap.Entry 对 Object[] 进行排序

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

我有一个类型为 Object[] 的列表里面有TreeMap.Entry<String, ChatDisplayDayWrapper>

key 是一个类似 2017-11-28 的字符串, 2017-11-27 , 2017-11-26 .

如何对列表进行排序以使键也反向排序
--> 2017-11-26 , 2017-11-27 , 2017-11-28

我尝试转换 StringDate把列表排序后我不知道如何写回它们。

代码

Object[] objectList = chatWrapper.getChatDayWrappers(); 

List<Date> listToSort = new ArrayList<Date>();

for (int i = 0; i <= objectList.size() - 1; i++) {
String day = objectList[i].key;
Date newDate = dfDate.parse(day);
listToSort.add(newDate)
}
getLogger().info("before sorting listToSort: " + listToSort);

listToSort = listToSort.sort { a, b ->
a <=> b
}
getLogger().info("After sorting listToSort: " + listToSort);

输出

对 listToSort 进行排序之前:

[Tue Nov 28 00:00:00 CET 2017, Mon Nov 27 00:00:00 CET 2017, Sun Nov 26 00:00:00 CET 2017]

对 listToSort 进行排序后:

[Sun Nov 26 00:00:00 CET 2017, Mon Nov 27 00:00:00 CET 2017, Tue Nov 28 00:00:00 CET 2017]

屏幕截图

enter image description here

最佳答案

Java 8

 List<TreeMap.Entry<String, ChatDisplayDayWrapper>> myList = Arrats.asList(objectList);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
Collections.sort(myList , (s1, s2) -> LocalDateTime.parse(s1.getKey(), formatter).
compareTo(LocalDateTime.parse(s2.getKey(), formatter)));

Java 7

 List<TreeMap.Entry<String, ChatDisplayDayWrapper>> myList = Arrays.asList(objectList);
static SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
public static Comparator<TreeMap.Entry<String, ChatDisplayDayWrapper>> myComparator = new Comparator<TreeMap.Entry<String, ChatDisplayDayWrapper>>() {

@Override
public int compare(TreeMap.Entry<String, TreeMap.Entry<String, ChatDisplayDayWrapper>>e1, Employee e2) {
return formatter .parse(s1.getKey()).
compareTo(formatter .parse(s2.getKey()))
}
};

Collections.sort(myList , myComparator);

我几乎是从 here 拿来的

关于java - 使用 TreeMap.Entry 对 Object[] 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47528355/

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