CodesJava

Easy learning with example program codes

How to get max 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.max() method will returns the maximum element of the given collection, according to the natural ordering of its elements.
Syntax:public static int max(Collection coll)

Example

package com.codesjava;
 
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.max(list);
        System.out.println("Employee with max salary: "+employee);
        }
}

Output

Employee with max salary: Name: Mahesh, Salary: 80000

Java Collections class examples

Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki