Example
package com.w3schools;
import java.util.Comparator;
import java.util.TreeSet;
class Employee{
private String name;
private int salary;
public Employee(String name, int salary){
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+", Salary: "+this.salary;
}
}
class SalaryComp implements Comparator<Employee>{
@Override
public int compare(Employee e1, Employee e2) {
if(e1.getSalary() > e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
public class Test {
public static void main(String args[]){
TreeSet<Employee> treeSet = new TreeSet<Employee>(new SalaryComp());
treeSet.add(new Employee("Jai",50000));
treeSet.add(new Employee("Mahesh",80000));
treeSet.add(new Employee("Vishal",60000));
treeSet.add(new Employee("Hemant",64000));
System.out.println("Least salary employee: "+treeSet.first());
}
} |
package com.w3schools;
import java.util.Comparator;
import java.util.TreeSet;
class Employee{
private String name;
private int salary;
public Employee(String name, int salary){
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+", Salary: "+this.salary;
}
}
class SalaryComp implements Comparator<Employee>{
@Override
public int compare(Employee e1, Employee e2) {
if(e1.getSalary() > e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
public class Test {
public static void main(String args[]){
TreeSet<Employee> treeSet = new TreeSet<Employee>(new SalaryComp());
treeSet.add(new Employee("Jai",50000));
treeSet.add(new Employee("Mahesh",80000));
treeSet.add(new Employee("Vishal",60000));
treeSet.add(new Employee("Hemant",64000));
System.out.println("Least salary employee: "+treeSet.first());
}
}
Output
Least salary employee: Name: Jai, Salary: 50000 |
Least salary employee: Name: Jai, Salary: 50000