Showing posts with label compare. Show all posts
Showing posts with label compare. Show all posts
Sunday, December 8, 2019
Friday, April 27, 2018
Java sort single field 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]
Subscribe to:
Posts (Atom)
Blueprint for self-improvement
To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...
-
Problem statement: There is a colony of 8 cells arranged in a straight line where each day every cell competes with its adjacent cells(neig...
-
Problem statement: Give an explanation for internal working of Set / HashSet in java. Answer: Reference
-
1. Think & Grow Rich - Napoleon Hill Focus: Wealth mindset & success Key Idea: Your thoughts shape your success 2. Atomic Habits - ...