How to get min element of a list of user defined objects?

The java.util.Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

Collections.min() method will returns the minimum element of the given collection, according to the natural ordering of its elements. Syntax:public static int min(Collection coll)

Example

package com.w3spoint;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
class Employee implements Comparable<Employee>{    
    private String name;
    private Integer 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;
    }
    @Override
    public int compareTo(Employee emp) {
    	return this.salary.compareTo(emp.getSalary());
    }
}
 
 
public class Test {
        public static void main(String args[]){
        List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee("Jai",50000));
        list.add(new Employee("Mahesh",80000));
        list.add(new Employee("Vishal",60000));
        list.add(new Employee("Hemant",64000));
        Employee employee=Collections.min(list);
        System.out.println("Employee with min salary: "+employee);
}
}

Output

Employee with min salary: Name: Jai, Salary: 50000

Java Collections class examples

Please follow and like us:
Content Protection by DMCA.com