Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

import java.util.

ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

class CustomPair {
int first;
int second;

public CustomPair(int first, int second) {


this.first = first;
this.second = second;
}
}

public class CustomPairSortingExample {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Taking user input for the pairs


System.out.print("Enter the number of pairs: ");
int n = sc.nextInt();

// Creating an ArrayList of CustomPairs


ArrayList<CustomPair> pairList = new ArrayList<>();

System.out.println("Enter " + n + " pairs (first and second separated by a


space):");
for (int i = 0; i < n; i++) {
int first = sc.nextInt();
int second = sc.nextInt();
pairList.add(new CustomPair(first, second));
}

// Sorting the list of pairs based on the first element


Collections.sort(pairList, Comparator.comparingInt(pair -> pair.first));

// Displaying the sorted pairs


System.out.println("Sorted pairs based on the first element:");
for (CustomPair pair : pairList) {
System.out.println(pair.first + " " + pair.second);
}

sc.close();
}
}

You might also like