Home  >  Core Java

Collections.max and Collections.min in Java

By Arvind Rai, May 26, 2013
In java Collections.max and Collections.min provides maximum and minimum element. The class whose object has been put in Collection must be comparable. On the basis of comparison logic Collections.min and Collections.max decides its result. Find the example.
CollectionsMaxMin.java
package com.concretepage.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsMaxMin {
    public static void main(String[] args) {
        User a1 = new User("AAAA");
        User a2 = new User("BBBB");
        User a3 = new User("CCCC");
        List<User> list = new ArrayList<User>();
        list.add(a1);
        list.add(a2);
        list.add(a3);
        //max element
        User u = Collections.max(list);
        System.out.println(u.getName());
        //min element
        u = Collections.min(list);
        System.out.println(u.getName());
    }
}
User.java
package com.concretepage.util;
public class User implements Comparable<User>  {
        private String name;
        public User(String name) {
                this.name = name;
        }
        public String getName() {
		return name;
        }
	@Override
	public int compareTo(User o) {
		return name.compareTo(o.getName());
	}
}
Output
CCCC
AAAA 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us