Your two ways to define the Comparator are equivalent. Your lambda version actually expands to the other version after compiling, because Comparator is a functional interface.

Here's a third shorter way to define your Comparator, using a static factory method on the Comparator interface:

PriorityQueue<Integer> heap3 = new PriorityQueue<>(Comparator.reverseOrder());
Answer from marstran on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › priority-queue-of-pair-in-java-with-examples
Priority Queue of Pair in Java with Examples - GeeksforGeeks
July 23, 2025 - PriorityQueue<Pair<K, V>> = new PriorityQueue<>(Comparator.comparing(Pair :: getKey)) ... Since Pair<K, V> class was the part of JavaFX and JavaFX was removed from JDK since JDK 11. So Pairs can be used till JDK 10. The below source code might not run on most of the online IDEs, better to try it on offline software. ... import java.util.*; import java.io.*; import javafx.util.Pair; class GFG { public static void main(String[] args) { // Priority Queue implementing min heap of Pairs // Creating instance of PriorityQueue by passing // Lambda expression as a constructor parameter.
Discussions

java 8 - Comparator as lambda expression in PriorityQueue - Stack Overflow
PriorityQueue constructor: PriorityQueue(int initialCapacity, Comparator comparator) 2021-07-20T03:59:32.23Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... New site design and philosophy for Stack Overflow: Starting February 24, 2026... 511 What is the point of the diamond operator (<>) in Java... More on stackoverflow.com
🌐 stackoverflow.com
lambda function doesn't work in priority_queue in c++ (when using [&]) - Stack Overflow
explicit priority_queue(const Compare& x = Compare(), Container&& y = Container()); As you can see, this involves default-constructing an object of type Compare. Prior to C++20, lambdas are not default constructible. More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
Reddit
reddit.com › r/learnjava › priorityqueue with lambda expression not working as expected?
r/learnjava on Reddit: PriorityQueue with lambda expression not working as expected?
December 27, 2021 -

I am working on this LeetCode problem and I'm using a PriorityQueue to maintain a heap based on the respective value in a HashMap like this

    Map<Character, Integer> countMap = new HashMap<>();
    PriorityQueue<Character> heap = new PriorityQueue<>((c1, c2) -> countMap.get(c2)-countMap.get(c1));

However I noticed in my code that when I modify values in countMap, the heap is not reordering itself using the Lambda expression (for example the input "bfrbs") and I can't understand why? Is there something I am misunderstanding? Here is what my full code looks like:

public String reorganizeString(String s) {
    StringBuilder sb = new StringBuilder();
    Map<Character, Integer> countMap = new HashMap<>();
    PriorityQueue<Character> heap = new PriorityQueue<>((c1, c2) -> countMap.get(c2)-countMap.get(c1));
    
    // O(N)
    for(char c : s.toCharArray()){
        countMap.put(c, countMap.getOrDefault(c, 0) + 1);
    }
    
    // O(N*Log(N))
    for(char c : countMap.keySet()){
        heap.add(c);
    }
    
    // O(N*Log(N)) ?
    while(countMap.get(heap.peek()) > 0){           
        char c1 = heap.remove();

        if(countMap.get(heap.peek()) == 0){
            if(countMap.get(c1) > 1) return "";
            sb.append(c1);
            break;
        }
        
        char c2 = heap.peek();
        
        if(sb.length() > 0 && sb.charAt(sb.length()-1) == c1){
            sb.append(c2);
            sb.append(c1);
        } else {
            sb.append(c1);
            sb.append(c2);                
        }
        
        countMap.put(c1, countMap.get(c1)-1);
        countMap.put(c2, countMap.get(c2)-1);
        heap.add(c1);
    }
    
    // O(N)
    return sb.toString();
}
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › PriorityQueue.html
PriorityQueue (Java Platform SE 8 )
3 weeks ago - Creates a PriorityQueue containing the elements in the specified sorted set. This priority queue will be ordered according to the same ordering as the given sorted set. ... ClassCastException - if elements of the specified sorted set cannot be compared to one another according to the sorted ...
🌐
CalliCoder
callicoder.com › java-priority-queue
Java Priority Queue Tutorial with Examples | CalliCoder
February 18, 2022 - Comparator<String> stringLengt... created using lambda expression like this => Comparator<String> stringLengthComparator = (s1, s2) -> { return s1.length() - s2.length(); }; Which can be shortened even further like this => ...
🌐
HackMD
hackmd.io › @csci0200 › Hk-2l0knd
Lab 6: Priority Queues and Comparators - HackMD
There is a built-in `compare` method on `Integers` that returns a negative number when the first number is smaller than the second, a positive number when the first is larger, and 0 if they are equal.
🌐
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.
Find elsewhere
🌐
Scaler
scaler.com › home › topics › java priorityqueue comparator
Java PriorityQueue Comparator - Priority queue
May 4, 2023 - It stores the data with the maximum priority at the top so you can extract your data according to its relevant importance. It uses a function that is used for comparison to decide the ordering of the elements and this function is called the ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › priority-queue-in-reverse-order-in-java
Priority Queue in Reverse Order in Java - GeeksforGeeks
July 23, 2025 - Lambda expression since Java 8 has come to use, lambda function names its input parameters a and b and returns (b-a), which is basically what the int comparator class does except it returns a-b. ... // Java program to demonstrate the // working ...
🌐
Stack Overflow
stackoverflow.com › questions › 68449329 › comparator-as-lambda-expression-in-priorityqueue
java 8 - Comparator as lambda expression in PriorityQueue - Stack Overflow
error: incompatible types: incompatible parameter types in lambda expression · PriorityQueue<int[]> pq = new PriorityQueue(10, ( (int[] a, int[] b) -> a[0] - b[0] )); java-8 · comparator · priority-queue · Share · Improve this question · Follow · edited Jul 20, 2021 at 3:58 ·
🌐
ConcretePage
concretepage.com › java › java-priorityqueue-comparator
Java PriorityQueue with Comparator
December 21, 2022 - public PriorityQueue(int initialCapacity, Comparator<? super E> comparator) Creates a PriorityQueue using specified initial capacity and the comparator to order the elements. If comparator is null, elements will be ordered in natural order.
🌐
YouTube
youtube.com › watch
Understanding Java Lambdas: Comparator with PriorityQueue - YouTube
Dive into the world of `Java Lambdas` and explore how to implement comparators in `PriorityQueue`. Learn the similarities and differences of using lambda exp...
Published   October 11, 2025
Views   0
🌐
HappyCoders.eu
happycoders.eu › algorithms › priorityqueue-java
Java PriorityQueue (+ Code Examples)
November 27, 2024 - In the last part of this tutorial series, I will show you how to implement a priority queue using a heap yourself. With the java.util.PriorityQueue class, the dequeue order results either from the elements' natural order¹ or according to a comparator¹ passed to the constructor.
🌐
OpenJDK
cr.openjdk.org › ~briangoetz › lambda › lambda-state-final.html
State of the Lambda
As an example of how the second rule comes into play, say the Collection and List interfaces provided different defaults for removeAll, and Queue inherits the default method from Collection; in the following implements clause, the List declaration would have priority over the Collection declaration inherited by Queue:
🌐
University of Hawaii
www2.hawaii.edu › ~esb › 2021fall.ics211 › nov22.pdf pdf
Outline
I am an Associate Professor at the University of Hawaii at Mānoa's Department of Information and Computer Sciences. I can be reached at esb@hawaii.edu. My office telephone number is +1-808-956-3891 · I joined UH in August, 1997. My most recent CV is here. Courses: Fall 2025: Introduction ...
🌐
Javatpoint
javatpoint.com › java-list-sort-lambda
Java List Sort Lambda - Javatpoint
Java List Sort Lambda with java tutorial, features, history, variables, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
YouTube
youtube.com › watch
How to use comparator in java using lambda expression
To learn more, please visit the YouTube Help Center: https://www.youtube.com/help
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › class-use › Comparator.html
Uses of Interface java.util.Comparator (Java Platform SE 8 )
October 20, 2025 - Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.