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 - The article discusses Java 8 Collectors, showing examples of built-in collectors, as well as showing how to build custom collector. ... Tips and best practices on using Java 8 lambdas and functional interfaces. ... public class Human { private String name; private int age; // standard constructors, getters/setters, equals and hashcode } Before Java 8, sorting a collection would involve creating an anonymous inner class for the Comparator used in the sort:
Discussions

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
(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
June 23, 2022
PriorityQueue with lambda expression not working as expected?
Can you first explain what are you trying to do and why? What's the expected output? EDIT: sorry, I didn't realize there is a link. Just a moment. EDIT2: So you are supposed to kind of "shuffle" the string. On lines 12-14, does this code work as you'd expect? Edit3: I ran your code with the input you gave and I printed the queue. Looks exactly what it should. Why not? More on reddit.com
🌐 r/learnjava
7
7
December 27, 2021
How do you make Java's PriorityQueue custom sort?
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://imgur.com/a/fgoFFis ) 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
10
5
November 10, 2021
🌐
Mkyong
mkyong.com › home › java8 › java 8 lambda : comparator example
Java 8 Lambda : Comparator example - Mkyong.com
August 5, 2015 - Actually, we can do it even simplier. Instead of writing for example · Comparator salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary()); listDevs.sort(salaryComparator.reversed());
🌐
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. Let's see a quick example of how to use a lambda expression to create a Comparator:
🌐
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
It has just one abstract method compare() which means you can pass a lambda expression where a Comparator is expected. Many Java programmers often ask me, what is the best way to learn lambda expression of Java 8? And, my answer is, of course by using it on your day to the day programming task.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java comparator with lambda
Java Comparator with Lambda (with Examples) - HowToDoInJava
February 6, 2023 - If we are not using lambda expressions, we can create a Comparator instance using an anonymous inner class. In the following example, we are creating a Comparator instance that compares the two instances of User class by their firstName property.
Find elsewhere
🌐
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.
🌐
Dev.java
dev.java › learn › lambdas › writing-comparators
Writing and Combining Comparators - Dev.java
February 24, 2023 - Suppose you need to create a comparator to compare strings of characters in a non-natural way: the shortest strings are lesser than the longest strings. ... You learned in the previous part that it is possible to chain and compose lambda expressions. This code is another example of such a composition.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lambda-expression-with-collections
Java Lambda Expression with Collections - GeeksforGeeks
July 11, 2025 - ... import java.util.*; public ... : " + al); // using lambda expression in place of comparator object Collections.sort(al, (o1, o2) -> (o1 > o2) ?...
🌐
Java Development Journal
javadevjournal.com › home › how to write a comparator as lambda expression
How to write a Comparator as Lambda Expression | Java Development Journal
August 26, 2021 - Now we have the basic setup done, lets see the different option to write a comparator as Lambda expression In Java. We will start by sorting the input based on a given parameter. In our first example, we will sort the customer by age.
🌐
TutorialsPoint
tutorialspoint.com › article › 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 - 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(new Employee(135, "Chaitanya", 40000.00)); System.out.println("Sorting the employee list based on the name"); // implementing lambda expression Collections.sort(list, (p1, p2) -> { return p1.name.compareTo(p2.name); }); for(Employee e : list) { System.out.println(e.id + " " + e.name + " " + e.salary); } } }
🌐
amitph
amitph.com › home › java › comparator with java lambda expression examples
Comparator with Java Lambda Expression Examples - amitph
November 22, 2024 - The inline implementation of the Comparator interface compares two Student objects based on the first name field. Java Lambda Expressions help reduce a lot of builder plate code blocks and make the code concise.
🌐
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 ...
🌐
Java2Blog
java2blog.com › home › core java › java 8 › java 8 lambda expression examples using comparator
Java 8 Lambda Expression examples using Comparator - Java2Blog
January 26, 2021 - We will sort Employee list by name using lambda expression, It will reduce complex Comparator syntax to simple line of code Create EmployeeMain.java
🌐
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 ...
🌐
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
Using Lambda expression: The Java 8 equivalent code using Lambda expression would look like this: 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(), ...
🌐
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.
🌐
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.
🌐
Delft Stack
delftstack.com › home › howto › java › java comparator lambda
Lambda Comparator in Java | Delft Stack
October 12, 2023 - Comparator<Employee> ee = new Comparator<Employee>() { // Overriding Comparator method to sort according to age @Override public int compare(Employee o1, Employee o2) { return o2.age - o1.age; } }; // Now Sorting the Method....