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 - //List.sort() since Java 8 listDevs.sort(new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o2.getAge() - o1.getAge(); } }); ... package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class TestSorting { public static void main(String[] args) { List<Developer> listDevs = getDevelopers(); System.out.println("Before Sort"); for (Developer developer : listDevs) { System.out.println(developer); } System.out.println("After Sort"); //lambda here!
๐ŸŒ
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, ...
๐ŸŒ
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) ?
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.
๐ŸŒ
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.
๐ŸŒ
GitHub
gist.github.com โ€บ Mountain-Biker โ€บ 444bd628563ff07dac22de5fe2e04238
Comparable, Comparator and lambda expression #Java #Comparable #Comparator ยท GitHub
Before Sorting : [John, Roger, Steven] After Sorting by age : [Roger, John, Steven] Java 8 provides new ways of defining Comparators by using lambda expressions, and the comparing() static factory method.
๐ŸŒ
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.
๐ŸŒ
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
๐ŸŒ
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
๐ŸŒ
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....
๐ŸŒ
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
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 781949 โ€บ java โ€บ Comparator-lambda
Comparator with lambda (Features new in Java 8 forum at Coderanch)
The range of arguments they are being tested on is too small to detect the error. You can read about object ordering in the Javaโ„ข Tutorials, which will tell you the correct thing to write. You can simply write Comparator<Integer> comp = Comparator.naturalOrder(); beausee Integer has a natural ordering.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ Comparator.html
Comparator (Java Platform SE 8 )
October 20, 2025 - @FunctionalInterface public interface Comparator<T> A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
๐ŸŒ
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.