0

I have been trying to implement PriorityQueue.

Here is what I wanted, sort according to the length of the String.

static class abc implements Comparator<String>
{

    @Override
    public int compare(String a, String b) {
        return a.length() - b.length();
    }

}

And the main Function:

    List<String> q = new ArrayList<String>();
    q.add("1");
    q.add("0111");
    q.add("11");
    q.add("151");
    q.add("121");

    Collections.sort(q, new abc());

This gave the perfect result.

But, when I used PriorityQueue instead of ArrayList

PriorityQueue<String> q = new PriorityQueue<>(10, new abc());

I don't get the required result.

When I print PQ:

System.out.println(q.toString());

[1, 151, 11, 0111, 121]

Also, since I want my List to be sorted overtime when I add a string, I would prefer PQ over ArrayList.

Can someone show with some example how to achieve this?

Thank you:)

Jay Patel
  • 1,266
  • 6
  • 20
  • 38

0 Answers0