It is necessary to sort the pairs, first by the first element (as in the code), and then by the second. That is, if the first elements of the pairs coincide, then it is necessary to sort by the second. thank

import java.io.*; import java.util.*; public class Main { public static void main(String args[]) throws IOException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); Pair mas[] = new Pair[n]; for(int i = 0; i < n; i++) { mas[i] = new Pair(in.nextInt(), in.nextInt()); } Arrays.sort(mas, (left, right)-> left.a - right.a); } } class Pair { final int a; final int b; public Pair(int a, int b){ this.a = a; this.b = b; } } 
  • You are welcome! And what is the question? - 0xdb
  • If the first element of the pair is the same, it is necessary to sort by the second) - Recil193i1
  • Well, you put the code. Is he doing something wrong? - 0xdb
  • does he only sort by a? and if the elements are left.a == right.a? - Recil193i1

2 answers 2

Never compare numbers by subtracting. Rumble overflow. For comparing two int there is a standard method Integer.compare()

 Arrays.sort(mas, (left, right)-> { // Сравнили left.a и right.a int res = Integer.compare(left.a, right.a); if (res == 0) // если они равны, то сравниваем left.b и right.b res = Integer.compare(left.b, right.b); return res }); 

Better yet, declare a comparator in the Pair class itself.

 class Pair { final int a; final int b; public Pair(int a, int b){ this.a = a; this.b = b; } public static int compare(Pair left, Pair right) { int res = Integer.compare(left.a, right.a); if (res == 0) res = Integer.compare(left.b, right.b); return res } } 

and give it to sort

 Arrays.sort(mas, Pair::compare); 
  • Thank! What you need - Recil193i1

According to en-SO, you can:

  1. creates stream and sorts it. Does not sort the source collection.
 pairs.stream().sorted(Comparator.comparing(Pair::a).thenComparing(Pair::b)); 
  1. Or so:
 Arrays.sort(mas, (p1, p2) -> { if (Integer.compare(p1.a, p2.a) == 0) { return Integer.compare(p1.a, p2.a); } else { return Integer.compare(p1.b, p2.b); } }); 
  1. Analogue of the first option, but sorts the original collection
 pairs.sort(Comparator.comparing(Person::a).thenComparing(Person::b));