Comparator#compareTo returns an int; while getTime is obviously long.

It would be nicer written like this:

.sort(Comparator.comparingLong(Message::getTime))
Answer from Eugene on Stack Overflow
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java โ€“ powerful comparison with lambdas
Java โ€“ Powerful Comparison with Lambdas | Baeldung
January 8, 2024 - In this tutorial, weโ€™re going to take a first look at the Lambda support in Java 8, specifically how to leverage it to write the Comparator and sort a Collection.
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2017 โ€บ 10 โ€บ java-8-lambda-comparator-example-for-sorting-list-of-custom-objects
Java 8 Lambda Comparator example for Sorting List of Custom Objects
Comparator sortingByName = (Student s1, Student s2)->s1.getName().compareTo(s2.getName()); Note: In Java 8, the List interface supports the sort() method so you need not to use the Comparator.sort(), instead you can use the List.sort() method.
๐ŸŒ
CodeJava
codejava.net โ€บ java-core โ€บ the-java-language โ€บ java-8-lambda-collections-comparator-example
How to use Java Lambda expression for sorting a List using comparator
Comparator<Book> titleComparator = new Comparator<Book>() { public int compare(Book book1, Book book2) { return book1.getTitle().compareTo(book2.getTitle()); } };And sort the above list like this: Collections.sort(listBooks, titleComparator);Print the list: System.out.println("\nAfter sorting by title:"); System.out.println(listBooks);Output: After sorting by title: [Code Complete-42.5, Effective Java-50.0, Head First Java-38.9, Thinking in Java-30.0] Since Java 8 with Lambda expressions support, we can write a comparator in a more concise way as follows:
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java8 โ€บ java 8 lambda : comparator example
Java 8 Lambda : Comparator example - Mkyong.com
August 5, 2015 - 3.4.2 Lambda expression to sort a List using their salary, reversed order. Comparator<Developer> salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary()); listDevs.sort(salaryComparator.reversed()); ... Developer [name=iris, salary=170000, age=55] Developer [name=jason, salary=100000, age=10] Developer [name=alvin, salary=80000, age=20] Developer [name=mkyong, salary=70000, age=33] ... Founder of Mkyong.com, passionate Java and open-source technologies.
๐ŸŒ
HowToDoInJava
howtodoinjava.com โ€บ home โ€บ java 8 โ€บ java comparator with lambda
Java Comparator with Lambda (with Examples) - HowToDoInJava
February 6, 2023 - ... The Comparator interface is used to sort a collection of objects that can be compared. The object comparison can be made using Comparable interface as well, but it restricts us by comparing objects in a specific single way only.
๐ŸŒ
Spring Framework Guru
springframework.guru โ€บ home โ€บ comparison and sorting with lambda
Comparison and Sorting with Lambda - Spring Framework Guru
January 5, 2021 - You can compare and sort Product objects based on various properties both with and without lambda expressions. However, when you use lambda expressions it makes your code concise and easier to read.
๐ŸŒ
Java8
java8.org โ€บ sort-a-collection-using-lambda-comparators
Sort a collection with lambda comparator - Java Resources
class Person { public String name; public int age; } // TODO we should add some persons to this list List<Person> persons = new ArrayList<>(); // Using a lambda expression to implement the Comparator Collections.sort(persons, (p1, p2) -> p1.name.compareTo(p2.name)); ... Collections.sort(persons, ...
Find elsewhere
๐ŸŒ
amitph
amitph.com โ€บ home โ€บ java โ€บ comparator with java lambda expression examples
Comparator with Java Lambda Expression Examples - amitph
November 22, 2024 - Learn how to use Java Lambda Expression-based Comparator to sort collections in forward and reverse directions easily.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-lambda-expression-with-collections
Java Lambda Expression with Collections - GeeksforGeeks
July 11, 2025 - Expression: - Using lambda expression in place of comparator object for defining our own sorting in collections. ... import java.util.*; public class Demo { public static void main(String[] args) { ArrayList<Integer> al = new ArrayList<Integer>(); al.add(205); al.add(102); al.add(98); al.add(275); al.add(203); System.out.println("Elements of the ArrayList " + "before sorting : " + al); // using lambda expression in place of comparator object Collections.sort(al, (o1, o2) -> (o1 > o2) ?
๐ŸŒ
GitHub
gist.github.com โ€บ Mountain-Biker โ€บ 444bd628563ff07dac22de5fe2e04238
Comparable, Comparator and lambda expression #Java #Comparable #Comparator ยท GitHub
We can build one simply by making use of the Comparator or Comparable interfaces. Let's use an example of a football team, where we want to line up the players by their rankings. ... public class Player { private int ranking; private String name; private int age; // constructor, getters, setters } Copy Next, we'll create a PlayerSorter class to create our collection, and attempt to sort it using Collections.sort:
๐ŸŒ
Medium
medium.com โ€บ @prithukathet โ€บ java-8-part-i-lambda-expressions-comparator-explained-like-never-before-fa246d627a28
Java 8 (Part I): Lambda Expressions & Comparator โ€” Explained Like Never Before | by Prithukathet | Medium
June 20, 2025 - Java knows this object can compare Student objects because it implements Comparator<Student>. That object is passed to Collections.sort(), which calls: compare(a, b) again and again during sorting.
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_advanced_sorting.asp
Java Advanced Sorting (Comparator and Comparable)
For example, if you have a list of cars you might want to sort them by year, the rule could be that cars with an earlier year go first. The Comparator and Comparable interfaces allow you to specify what rule is used to sort objects.
๐ŸŒ
Java Guides
javaguides.net โ€บ 2020 โ€บ 04 โ€บ java-8-lambda-sort-list-in-ascending-and-descending-order.html
Java 8 Lambda - Sort List in Ascending and Descending Order | Comparator Example
September 14, 2020 - class MySort implements Comparator < Employee > { @Override public int compare(Employee o1, Employee o2) { return (int)(o2.getSalary() - o1.getSalary()); } } Note that we have done a single line of change to sort Employee by their salary in descending order. return (int)(o2.getSalary() - o1.getSalary()); In this example, we will see how to sort a list of employees by name in ascending and descending order using Lambda Expressions: package com.java.tutorials.sorting; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortLi
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-write-the-comparator-as-a-lambda-expression-in-java
How to write the comparator as a lambda expression in Java?
In the below example, we can sort the employee list by name using the Comparator interface. import java.util.ArrayList; import java.util.Collections; import java.util.List; class Employee { int id; String name; double salary; public Employee(int id, String name, double salary) { super(); this.id = id; this.name = name; this.salary = salary; } } public class LambdaComparatorTest { public static void main(String[] args) { List<Employee> list = new ArrayList<Employee>(); // Adding employees list.add(new Employee(115, "Adithya", 25000.00)); list.add(new Employee(125, "Jai", 30000.00)); list.add(ne
๐ŸŒ
Oracle
oracle.com โ€บ java โ€บ technical details
Java 8: Lambdas, Part 2
As a matter of fact, this โ€œI ... out of the box. On the Comparator class, a comparing method takes a function (a lambda) that extracts a comparison key out of the object and returns a Comparator that sorts based on that....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-comparator-interface
Java Comparator Interface - GeeksforGeeks
Final list shows sorted order by both name and age fields. Java 8 introduced a more simple way to write comparators using lambda expressions.
Published ย  April 20, 2016
๐ŸŒ
Java67
java67.com โ€บ 2014 โ€บ 11 โ€บ java-8-comparator-example-using-lambda-expression.html
How to implement Comparator and Comparable in Java with Lambda Expression & method reference? Example | Java67
To complete these tasks we need to create two custom Comparator implementations, one to sort TrainingCourse by title and the other to sort it by price. To show the stark difference in the number of lines of code you need to do this prior to Java 8 and in JDK 1.8, I have implemented that two Comparator first using Anonymous class and later using the lambda expression.
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ lambda expression as a comparator?
r/javahelp on Reddit: lambda expression as a comparator?
September 23, 2023 -
  public static int longestStrChain(String[] words) {
    Arrays.sort(words, (a, b) -> a.length() - b.length());
    HashMap<String, Integer> dp = new HashMap<>();
    int max_chain = 0;
    for (String word : words) {
        dp.put(word, 1);
        for (int i = 0; i < word.length(); i++) {
            String prev_word = word.substring(0, i) + word.substring(i + 1);
            if (dp.containsKey(prev_word)) {
                dp.put(word, Math.max(dp.get(word), dp.get(prev_word) + 1));
            }
        }
        max_chain = Math.max(max_chain, dp.get(word));
    }
    return max_chain;
}

Can someone help me understand how doesArrays.sort(words, (a, b) -> a.length() - b.length()); actually work? they said that it's for sorting String array, descending order. I don't even know how this
does work i use the debugging tool and seems like it's looping through the array, i was fine with the for-each-loop sorting until this came in.

 for(int i = 0; i<words.length;i++) {
        for (int j = i; j < words.length; j++) {
            if (words[j].length()<words[i].length()){
                swap(j,i,words);

            }

could someone please explain this to me? the Array.sort is looping too so maybe it's the same?

Top answer
1 of 2
2
the Array.sort is looping too so maybe it's the same? Yes, the Arrays.sort(...) method is basically doing the same thing as the for loop you describe; except that instead of for loops, it will use a more efficient sorting algorithm, such as merge sort . The lambda is a shorthand way of writing a Comparator class. The comparator has a single compare method, which takes two parameters, and basically says how those two object should be ordered. The sorting algorithm uses the comparator to sort the array -- basically the same as the code in your if statement's condition.
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.