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
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()));
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);
}