Good day!

There is a class of Chat:

public class Chat { private String id; private String title; private String author; private String[] participants; private String lastMessage; private long created; private long updated; } 

There is a list:

 ArrayList<Chat> chats = new ArrayList<Chat>(); 

The list contains several objects.

You must sort this list by updated field descending.

How to do it right?

3 answers 3

You can use Collections.sort(...) and Comparator :

 Collections.sort(chats, new Comparator<Chat>() { @Override public int compare(Chat o1, Chat o2) { return Long.compare(o2.getUpdated(), o1.getUpdated()); } }); 

The design can be simplified using lambda:

 Collections.sort(chats, (o1, o2) -> Long.compare(o2.getUpdated(), o1.getUpdated())); 

    Sort using Java 8 Stream API

      List<Chat> collect = new ArrayList<Chat>(){{ add(new Chat(4)); add(new Chat(3)); add(new Chat(6)); add(new Chat(8)); add(new Chat(1)); add(new Chat(2)); }}; List<Chat> res = collect .stream() .sorted((f1, f2) -> Long.compare(f2.getUpdated(), f1.getUpdated())) .collect(Collectors.toList()); res.forEach(f -> System.out.println(f.getUpdated())); 

    Option 2:

      collect.sort((f1, f2) -> Long.compare(f2.getUpdated(), f1.getUpdated())); collect.forEach(f -> System.out.println(f.getUpdated())); 

    conclusion

     8 6 4 3 2 1 
    • Thanks for the answer, did not work. Android Studio swears. Can I use the Java 8 Stream API for Android? - Miller777
    • as far as I know, no. but 2 way should work - Senior Pomidor
    • @ Miller777 Stream API can be used starting from API 24 - pavlofff

    Use a comparator to sort. For example:

     class Test{ public static void main (String[] args){ ArrayList<Chat> chats = new ArrayList<Chat>(); chats.add(new Chat(5)); chats.add(new Chat(8)); chats.add(new Chat(3)); chats.add(new Chat(2)); chats.add(new Chat(4)); chats.add(new Chat(10)); chats.add(new Chat(8)); Collections.sort(chats, Chat.compare); for(Chat chat: chats) System.out.println(chat); } } class Chat{ private String id; private String title; private String author; private String[] participants; private String lastMessage; private long created; private long updated; public Chat(long updated){ this.updated = updated; } public static final Comparator<Chat> compare = new Comparator<Chat>() { @Override public int compare(Chat chat1, Chat chat2) { return Long.compare(chat1.updated, chat2.updated); } }; public String toString(){ return "Updated = " + this.updated; } } 

    Conclusion:

     Updated = 2 Updated = 3 Updated = 4 Updated = 5 Updated = 8 Updated = 8 Updated = 10 

    This answer is based on: https://ru.stackoverflow.com/a/468299/235436

    • Thank you, earned! Had to raise min. API level from 16 to 19, otherwise Android Studio swore. - Miller777