Getting the minimum and maximum element of the given collection

Getting the minimum element of the given collection, according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator (that is, comp.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).


Getting the maximum element of the given collection, according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator (that is, comp.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).


package collection.demos;



import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;



class Emp{

    String name;

    int salary;



    public Emp(String name, int salary) {

        this.name = name;

        this.salary = salary;

    }

    @Override

    public String toString() {

        return "Emp [" +name + ", "+ salary + "]";

    }

}



class MyComparator1 implements Comparator<Emp>{

    public int compare(Emp o1, Emp o2) {

        return o1.salary-o2.salary;

    }

}

public class GettingMinMaxEelementUsingComparator {

    public static void main(String[] args) {

        ArrayList<Emp> list=new ArrayList<Emp>();

        list.add(new Emp("ABC",345345));

        list.add(new Emp("Syndi",454544));

        list.add(new Emp("Upal",332222));

        list.add(new Emp("Tryno",875454));

        System.out.println("Element of Min salary : "+Collections.min(list, new MyComparator1()));

        System.out.println("Element of Max salary : "+Collections.max(list, new MyComparator1()));

    }

}



/*

OUTPUT : 

Element of Min salary : Emp [Upal, 332222]

Element of Max salary : Emp [Tryno, 875454]

 */

No comments:

Popular Posts