Pairs in TreeSet - Java - Sorting Pairs in Set with Comparator Interface - Graphs
The following is an implementation of pairs inside set in Java which is useful in solving graphs, Trees related problem in competitive programming. We can implement easily in CPP but Java provides more flexibility of how to implement as our wish like sorting the pairs in set in descending order as our wish based on our usage. Here is my implementation of pairs inside TreeSet along with sorting in ascending order based on the first and second value in a pair. In this, I used Comparator interface and override compare function.
import java.util.*;
import java.io.*;
import java.lang.*;
public class Solution {
static class Pair
{
public int a,b;
void initPair(Integer a,Integer b)
{
this.a = a;
this.b =b;
}
}
public static void main(String[] args) {
Set <Pair>hs = new TreeSet<Pair>(new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if(o1.a-o2.a==0)
{
if(o1.b==o2.b)
return 1;
else
return o1.b-o2.b;
}
return o1.a-o2.a;
}
});
System.out.println("Enter the number pairs into the Set");
Scanner s = new Scanner(System.in);
int n= s.nextInt();
System.out.println("Enter the pairs");
for(int i=0;i<n;i++)
{
Pair pr = new Pair();
int x,y;
x = s.nextInt();
y= s.nextInt();
pr.initPair(x,y);
hs.add(pr);
}
for(Pair p : hs){
System.out.println(p.a+" "+p.b);
}
}
}
Input (stdin)
5
3 56
1 4
1 6
5 4
4 5
Your Output (stdout)
1 4
1 6
3 56
4 5
5 4
Go Through Tutorial Lists in HashMap:
https://www.unleashcodingskills.com/2018/05/lists-in-hashmap-example-zoho-technical.htmlHappy Coding...............
Thanks for letting us to know I understand it well
ReplyDelete