How can I find the maximum element contained within a Collection?

Brandon Rohlfs

Finding the maximum element within a Collection is easy. The following method can be used which can be found within the Collections class.

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
This method returns the maximum element of the given Collection according to the natural ordering of it's elements. This means that all elements must implement the Comparable interface. With the following code below the implementation of the Comparable interface is already taken care of since the class Byte already implements this interface.
import java.util.Set;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; 

public class Max{
 public static void main(String[] args){
  Collection<Byte> numl = new ArrayList<Byte>(); 
  numl.add(new Byte("2"));
  numl.add(new Byte("6"));
  numl.add(new Byte("3"));
  numl.add(new Byte("1"));
  numl.add(new Byte("5"));
  numl.add(new Byte("4"));
  System.out.print("Max element is " + getMax(numl));   
 }
 public static Byte getMax(Collection<Byte> c){
   return Collections.max(c); 
 }
}

If the element type being store within the Collection is user defined, implementation of the Comparable interface must be provided.

import java.util.Set;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; 

public class Max{
 public static void main(String[] args){
  Collection<Num> numl = new ArrayList<Num>(); 
  numl.add(new Num("2"));
  numl.add(new Num("6"));
  numl.add(new Num("3"));
  numl.add(new Num("1"));
  numl.add(new Num("5"));
  numl.add(new Num("4"));
  System.out.print("Max element is " + getMax(numl).getNum());   
 }
 public static Num getMax(Collection<Num> c){
   return Collections.max(c); 
 }
}
class Num implements Comparable<Num>{
 private String i; 
 public Num(String i){
  this.i = i; 
 }
 public int compareTo(Num num){
  int x = i.compareTo(num.i);
  return x; 
 }
 public String getNum(){
  return i; 
 }
}
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact