Jass_Manak's blog

By Jass_Manak, history, 5 years ago, In English

I came across a question where I have to store to pair in PriorityQueue in Java. But Java does not have anything like make_pair in C++. What can be the alternate used in Java for making a pair?

  • Vote: I like it
  • +1
  • Vote: I do not like it

| Write comment?
»
5 years ago, # |
  Vote: I like it +15 Vote: I do not like it

The simplest way would probably be making your own pair class and defining a custom comparator.

»
5 years ago, # |
  Vote: I like it +13 Vote: I do not like it

Still not available in Java standard library. So all you need is to switch to Scala :)

  import java.util.PriorityQueue
  
  val pq = new PriorityQueue[(Int, String)]
  pq.add((1, "one"))
  pq.add((2, "two"))
»
5 years ago, # |
  Vote: I like it +8 Vote: I do not like it

You need to create a java class for pair an implementation is given below :

class pair implements Comparable{ int a,b;

public pair(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public int compareTo(pair o) {
        if(this.a==o.a)
            return this.b - o.b;
        return this.a - o.a;
    }
}

pair class implements comparable interface because priority queue will use this interface compareTo method to compare elements.

you can define priority queue as follows

PriorityQueue<pair> pq = new PriorityQueue<>();
    pq.add(new pair(1,2));
»
5 years ago, # |
  Vote: I like it +8 Vote: I do not like it

Abit weird method but if the numbers in your pair are small enough, you insert then into your priority queue by inserting a*(constant)+b.