Java single field sort using Comparator.


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

class SortBySalary implements Comparator<Human> {
@Override
public int compare(Human o1, Human o2) {
if (o1.salary > o2.salary)
return 1;
if (o1.salary < o2.salary)
return -1;
return 0;
}

}

class Human {
String name;
int age;
double salary;

public Human(String n, int a, double s) {
this.name = n;
this.age = a;
this.salary = s;
}

public Human() {
}

public String toString() {
return this.name + " " + this.age + " " + this.salary;
}

}

public class ComparatorExe {
public static void main(String[] args) {

List<Human> l = new ArrayList();
Human h1 = new Human("ritesh", 12, 6000);
Human h2 = new Human("raju", 18, 5000);
Human h3 = new Human("ishaan", 10, 7000);
Human h4 = new Human("yuyu", 15, 333);
Human h5 = new Human("yuyu", 17, 333);
Human h6 = new Human("yuyu", 13, 333);
l.add(h1);
l.add(h2);
l.add(h3);
l.add(h4);
l.add(h5);
l.add(h6);

System.out.println(l);

Collections.sort(l, new SortBySalary());
System.out.println(l);
}

}


Output: 
[ritesh 12 6000.0, raju 18 5000.0, ishaan 10 7000.0, yuyu 15 333.0, yuyu 17 333.0, yuyu 13 333.0] [yuyu 15 333.0, yuyu 17 333.0, yuyu 13 333.0, raju 18 5000.0, ritesh 12 6000.0, ishaan 10 7000.0]

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation