Created
June 27, 2017 06:53
-
-
Save anil477/839c733b7d23c477d7aad6b3d4365574 to your computer and use it in GitHub Desktop.
Using Comparator to specify custom sorting - 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Check this also https://gist.github.com/anil477/da64f09ddd9323c9858f86eaffe9610b | |
import java.util.*; | |
class Employee implements Comparable<Employee> { | |
private String name; | |
private int age; | |
private int salary; | |
public Employee(String name, int age, int salary) { | |
this.name = name; | |
this.age = age; | |
this.salary = salary; | |
} | |
@Override | |
public int compareTo(Employee employee) { | |
return employee.salary - this.salary; | |
} | |
public String toString() { | |
return String.format("(%s, %d, %d)", name, age, salary); | |
} | |
} | |
class Test{ | |
public static void main(String[] args){ | |
ArrayList<Employee> list = new ArrayList<Employee>(); | |
list.add(new Employee("Anil", 26, 1234)); | |
list.add(new Employee("Sunil", 21, 123)); | |
list.add(new Employee("Arch", 20, 533)); | |
System.out.println("Before sorting: " + list); | |
Collections.sort(list); | |
System.out.println("After sorting: " + list); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment