Sep 23

Say you have a class with a number of properties, and you then have a Collection of these beans and you want to find the bean with the largest value of one of the properties.

Instead of using a loop to go through the collection to find the largest element based on our condition we can instead use the Collections.max() method. You just need to pass it the collection to search for the max and a Comparator that defines how two beans should be compared.


MyBean max = Collections.max(collectionOfMyBean, 
   new Comparator< MyBean >() {
      public int compare(MyBean bean1, MyBean beans2) {

           // We'll assume for the sake of this example 
           // that the bean property is Comparable.
           // If its not then you would just need to 
           // adjust how the 2 values are compared

           return bean1.getProperty().compareTo(bean2.getProperty());
       }
    });

written by objects \\ tags: , , , ,

Sep 25

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyBean implements Comparable<MyBean>
{
   private int value;

   public MyBean()
   {
   }

   public MyBean(int value)
   {
      setValue(value);
   }

   public int getValue()
   {
      return value;
   }

   public void setValue(int value)
   {
      this.value = value;
   }

   public int compareTo(MyBean other)
   {
       return value - other.value;
   }

   public String toString()
   {
	   return Integer.toString(value);
   }
   
   public static void main(String[] args)
   {
      List<MyBean> listOfMyBeans = new ArrayList<MyBean>();
      listOfMyBeans.add(new MyBean(5));
      listOfMyBeans.add(new MyBean(1));
      listOfMyBeans.add(new MyBean(4));

      Collections.<MyBean>sort(listOfMyBeans);

      System.out.println(listOfMyBeans);
   }
} 

written by objects \\ tags: , , , ,