Pairs in TreeSet - Java - Sorting Pairs in TreeSet with Comparator Interface-Generic Class object in set Java -Generic class object sorting in java - Graphs - UCS - Unleash-Coding-Skills

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);
}
for(Pair p : hs){
System.out.println(p.a+" "+p.b);
}
}
}
Input (stdin)
``````5
3 56
1 4
1 6
5 4
4 5``````
``````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.html

Happy Coding...............

1 comment:

1. Thanks for letting us to know I understand it well