Search code examples
javasortingarraylistpriority-queue

Java Priority Queue with ArrayLists and Pairs


I'm looking for simple way to build a Priority Queue in Java. I've built an ArrayList<Pair>, and each Pair instance contains an X and Y values.

class Pair {
    private final Float xVal;
    private final Float yVal;

    public Pair(Float aXVal, Float aYVal) {
        xVal = aXVal;
        yVal = aYVal;
    }

    public float getX() {
        return xVal;
    }

    public float getY() {
        return yVal;
    }
}

My ArrayList looks like:

ArrayList<Pair> listOfPoints;

Using the ArrayList listOfPoints, I wanted to build two priority queues:

  • One that is sorted on the x Values from low to high.
  • One that is sorted on the y Values form low to high.

I was looking for a simple way to do this using Lambda expressions.

I did look at this question on Stack Overflow, and I found this code:

PriorityQueue<String> pq=
                    new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());

I think this is close to what I want.

I was trying to implement the following:

PriorityQueue<Pair> xSorted = new PriorityQueue<Pair>(numOfPoints, (x1,x2) -> Need Help Here);

How do I access Pair in order to have it compare x1 and x2?

Note, that nummberOfPoints I was setting to the length of ArrayList<Pair> listOfPoints.


Solution

  • For the natural (ascending) order based on xVal:

    PriorityQueue<Pair> pq= new PriorityQueue<>(Comparator.comparingDouble(Pair::getX));
    
    

    For the reversed (descending) order based on xVal:

    PriorityQueue<Pair> pq= new PriorityQueue<>(Comparator.comparingDouble(Pair::getX).reversed());
    
    

    You can use the same approach for yVal or any other comparable field, by using Comparator API.