Advertisement
jasonpogi1669

Sort List of Tuples in Java

Aug 7th, 2022
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Main {
  5.     public static void main(String[] args) {
  6.         ArrayList<Tuple> arr = new ArrayList<>();
  7.        
  8.         arr.add(new Tuple(1, 2, 3));
  9.         arr.add(new Tuple(1, 2, 100));
  10.         arr.add(new Tuple(1, 2, 1));
  11.        
  12.         Collections.sort(arr);
  13.        
  14.         for (Tuple tp : arr) {
  15.             System.out.println(tp.first + " " + tp.second + " " + tp.third);
  16.         }
  17.     }
  18.    
  19.     static class Tuple implements Comparable<Tuple> {
  20.         int first;
  21.         int second;
  22.         int third;
  23.        
  24.         Tuple(int first, int second, int third) {
  25.             this.first = first;
  26.             this.second = second;
  27.             this.third = third;
  28.         }
  29.        
  30.         @Override
  31.         public int compareTo(Tuple other) {
  32.             if (this.first < other.first) {
  33.                 return -1;
  34.             }
  35.             if (this.second < other.second) {
  36.                 return -1;
  37.             }
  38.             if (this.third < other.third) {
  39.                 return -1;
  40.             }
  41.             return 1;
  42.         }
  43.     }
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement