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
🌐
Javabrahman
javabrahman.com › java-8 › the-complete-java-8-comparator-tutorial-with-examples
The Complete Java 8 Comparator Tutorial with examples
Java 8's Comparator as an assignment target for LambdaExpressions Given the fact that its a functional interface, an instance of a Comparator can now be created in Java 8 with a lambda expression specifying its comparison logic.
🌐
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?
December 6, 2019 - 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
Discussions

Java 8 Lambda: Comparator - Stack Overflow
Anonymous Classes how to sort a ... of Java 8 using inner Classes. An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. Comparator timeCompare = new Comparator() { @Override public int compare(Employee e1, Employee e2) { return e1.getCreationTime().compareTo( e2.getCreationTime() ); } }; ... A lambda expression ... More on stackoverflow.com
🌐 stackoverflow.com
lambda expression as a comparator?
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. More on reddit.com
🌐 r/javahelp
8
1
September 23, 2023
What is the correct way to sort a list using a Java lambda comparator, and how can I fix the type mismatch error? - TestMu AI Community
I’m trying to sort a List using ... has something to do with how Comparator expects the return type, but I’m not sure how to properly use a Java lambda comparator when the compariso...... More on community.testmu.ai
🌐 community.testmu.ai
0
April 4, 2025
(Java) Lambda Method using Comparable
The code is nonsensical in many ways. Comparable is an interface for creating objects that can be compared: this one compared to another one (the o parameter in you code). There’s no point in creating Comparable lambda, and doing so in Student class gets all the more confusing since you are not using the o parameter at all. You would get more sensible example by creating Comparator lambda, preferably outside Student class. That lambda would compare two students given as parameters. More on reddit.com
🌐 r/learnprogramming
1
1
December 24, 2021
🌐
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.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java comparator with lambda
Java Comparator with Lambda (with Examples) - HowToDoInJava
February 6, 2023 - Learn to create a Comparator instance with lambda expressions, method references and chaining multiple comparators for complex comparisons.
🌐
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
You can implement a Comparator using lambda expression because it is a SAM type interface. It has just one abstract method compare() which means you can pass a lambda expression where a Comparator is expected.
🌐
Medium
medium.com › @rkdixit3 › java-8-java-comparator-with-lambda-3797ccf0da59
Java 8 | Java Comparator with Lambda | by Rajesh Dixit | Medium
January 8, 2020 - Java 8 | Java Comparator with Lambda Comparator is used when we want to sort a collection of objects which can be compared with each other. This comparison can be done using a Comparable interface as …
🌐
Dev.java
dev.java › learn › writing-and-combining-comparators
Writing and Combining Comparators
February 24, 2023 - Leveraging inheritance in Java applications. ... Creating and using interfaces. ... Working with parameterized types. ... Using Lambda Expressions to improve the readability of your code.
Find elsewhere
🌐
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.
🌐
Vertex Academy
vertex-academy.com › tutorials › en › java-8-lambda-comparator-example
Java 8 Lambda: Comparator Example • Vertex Academy
January 26, 2018 - Before Java 8 was released, we had to create an anonymous inner class for the Comparator to sort a collection. Then we had to transfer the inner class and the collection to Collections.sort ... In Java 8, we use the Lambda expression instead of creating an anonymous inner class for the Comparator.
🌐
Coderanch
coderanch.com › t › 781949 › java › Comparator-lambda
Comparator with lambda (Features new in Java 8 forum at Coderanch)
May 30, 2024 - 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.
🌐
GitHub
gist.github.com › Mountain-Biker › 444bd628563ff07dac22de5fe2e04238
Comparable, Comparator and lambda expression #Java #Comparable #Comparator · GitHub
Java 8 provides new ways of defining Comparators by using lambda expressions, and the comparing() static factory method.
🌐
Coderanch
coderanch.com › t › 656713 › java › Type-inferencing-Lambdas-chained-Comparators
Type inferencing with Lambdas and chained Comparators (Java in General forum at Coderanch)
October 16, 2015 - Object does not have an age field, so it can't let you use that lambda. Jeanne's method references work because the method reference has a definite type that the compiler can use to infer the type parameters, so it knows what type to use when implementing the ToIntFunction. Exactly the same thing applies to the comparing methods you call, although they have extra type parameters.
🌐
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) ?
🌐
TestMu AI Community
community.testmu.ai › ask a question
What is the correct way to sort a list using a Java lambda comparator, and how can I fix the type mismatch error? - TestMu AI Community
April 4, 2025 - I’m trying to sort a List<Message> using a lambda expression in Java 8 like this: List<Message> messagesByDeviceType = new ArrayList<>(); messagesByDeviceType.sort((Message o1, Message o2) -> o1.getTime() - o2.getTime()…
🌐
Oreate AI
oreateai.com › blog › understanding-java-lambda-comparators-a-friendly-guide › 9d7851e1f29dc443e1a210a1e891aa09
Understanding Java Lambda Comparators: A Friendly Guide - Oreate AI Blog
January 15, 2026 - Explore how Java's lambda expressions simplify creating comparators for object sorting while enhancing code readability and flexibility.
🌐
Baeldung
baeldung.com › home › java › guide to java comparator.comparing()
Guide to Java Comparator.comparing() | Baeldung
January 8, 2024 - The Comparator interface can also effectively leverage Java 8 lambdas.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
October 20, 2025 - Java™ Platform Standard Ed. 8 ... This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. @FunctionalInterface public interface Comparator<T>
🌐
Reddit
reddit.com › r/learnprogramming › (java) lambda method using comparable
r/learnprogramming on Reddit: (Java) Lambda Method using Comparable
December 24, 2021 -

Hello all,

Here is my code in question:

public int lambdaCompare(Student lambdaCheck){
Comparable<Student> studentCompare =
(o) -> this.getStudentID() - lambdaCheck.getStudentID();
int result = studentCompare.compareTo(lambdaCheck);
return result;
}

I wrote this method to practice my lambda expressions, but I don't fully understand it. Is the o parameter linked to this.getStudentID() or lambdaCheck.getStudentID(). I think its the first one?

When I set the expression equal to result and pass the parameter lambdaCheck. What am I actually doing?

Having just the single parameter(o) is blowing up my brain.