GFG Sorting Comparable and Comparator interface

 package com.company;


import java.awt.*;
import java.util.*;
import java.util.List;

class point{
int x,y;
public point(int x, int y) {
this.x = x;
this.y = y;
}
}
class myComparator implements Comparator<point>{
public int compare(point p1, point p2){
return p1.x - p2.x;
}
}
//Implementing Comparable interface
//class point implements Comparable<point> {
// int x, y;
// public point(int x, int y) {
// this.x = x;
// this.y = y;
// }
// public int compareTo(point p){
// return x - p.x;
// }
//}

//All even number comes first than all odd numbers
class MyClass implements Comparator<Integer> {
@Override
public int compare(Integer a, Integer b) {
return a % 2 - b % 2;
}
}

public class Main {

public static void main(String[] args) {
// int[] array = {1,3,4,2,98,78};
//// Arrays.sort(array);
// Arrays.sort(array,2,5);
// System.out.println(Arrays.toString(array));
// Integer[] arr = {5, 10, 20, 3, 12};
// Arrays.sort(arr, new MyClass());
// System.out.println(Arrays.toString(arr));
List<point> list = new ArrayList<point>();
list.add(new point(10, 67));
list.add(new point(20,7));
list.add(new point(5,78));
Collections.sort(list, new myComparator());
for (point p:list
) {
System.out.println(p.x + " " + p.y);
}
// System.out.println(list);
// Collections.sort(list, Collections.reverseOrder());
// System.out.println(list);
}
}

Comments