How to implement Pair Class in Java?

Is there any inbuilt library for pair class in java like in c++? If not how to we implement pair class in java and how can we do pair sort with respect to the first element and pair sort with respect to the second element in java?

Yes,It is there in Java also.

It is not work in Java 7,But It is available in Java 8.

We need to store the values into Pair using the parameterized constructor provided by the “javafx.util.Pair” class.

Note that the “(Key,Value)” pair used in HashMap/TreeMap. Here, <Key, Value> simply refers to a pair of values that are stored together.

Check Here Once
: Pair Class in Java - GeeksforGeeks

This should function similar to the C++ pair and be good enough for competitive programming purposes

class Pair<S extends Comparable<S>, T extends Comparable<T>> implements Comparable<Pair<S, T>> {
    S first;
    T second;
    
    Pair(S f, T s) {
        first = f;
        second = s;
    }

    @Override
    public int compareTo(Pair<S, T> o) {
        int t = first.compareTo(o.first);
        if (t == 0) return second.compareTo(o.second);
        return t;
    }
    
    @Override
    public int hashCode() {
        return (31 + first.hashCode()) * 31 + second.hashCode();
    }
    
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) return false;
        if (o == this) return true;
        Pair p = (Pair) o;
        return first.equals(p.first) && second.equals(p.second);
    }
    
    @Override
    public String toString() {
        return "Pair{" + first + ", " + second + "}";
    }
}
3 Likes

This is my implementation. This is what I use.

public static class Point extends Object implements Comparable<Point> {

//variables are final for a reason
//delete the previous point and add a new modified one
private final int x;
private final int y;

public Point(){}

public Point(int x, int y){
	this.x = x;
	this.y = y;
}

public int getX(){return this.x;}
public int getY(){return this.y;}

public void show(){
	System.out.println("[" + this.getX() + " , " + this.getY() + "]");
}

public int distance(Point p2){

	double d = Math.pow(this.x - p2.x, 2) + Math.pow(this.y - p2.y, 2);

	return (int)Math.sqrt(d);
}



/* This method is called while sorting
 * by default it sorts in ascending order
 * of x and y
 */
@Override
public int compareTo(Point p){

	if(this.x != p.x)
		return this.x = p.x;

	return this.y - p.y;
}

//https://www.artima.com/lejava/articles/equality.html
@Override
public boolean equals(Object obj){
	if(super.equals(obj)) return true;
	if(!obj instanceof Point) return false;

	Point that = (Point)obj;
	return this.x == that.x && this.y == that.y;
}

//see the link above
@Override 
public int hashCode() {
    return (59 * (59 + getX()) + getY());
}

@Override
public String toString(){
	return "[" + this.getX() + " , " + this.getY() + "]";
} 

}

But when I import JavaFX library in codechef IDE it was showing a syntax error.