Want to order chats in ArrayList by timestamp using Comparator, but it's not working and I don't know why

前端 未结 2 1804
别那么骄傲
别那么骄傲 2021-01-21 17:55

I have implemented a chat function in my app and it\'s working fine, only problem is that now I want the chats to be ordered by timestamp, so that the newest ones c

相关标签:
2条回答
  • 2021-01-21 18:18

    You can simply use Java8 feature to compare the element as below:

    List<ChatList> unique = list.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparing(ChatList::getTimestamp))),ArrayList::new));
    unique.forEach((k) -> System.out.println(k.getTimestamp()));
    
    0 讨论(0)
  • 2021-01-21 18:35

    You are sorting collection in ascending order by using Long.compare(). For showing latest chat you need to change the compare method as

    public int compare(Chatlist o1, Chatlist o2) {
                        return o1.getTimestamp() < o2.getTimestamp() ? 1 : 
                       (o1.getTimestamp == o2.getTimestamp() ? 0 : -1);
    }
    
    0 讨论(0)
提交回复
热议问题