Oct 01

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 smallest value of one of the properties.

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


MyBean max = Collections.min(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 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: , , , ,

Oct 01

You have a few options, either return them in an array, or a Map or use another class to store the values and return that.


/** Use an array to return two value */

public int[] methodReturningTwoInts()
{
   int a = getA();
   int b = getB();
   return new int[] { a, b };
}

/** Use a Map to return two value */

public Map<String, Integer> methodReturningTwoInts()
{
   int a = getA();
   int b = getB();
   Map<String, Integer> result = new HashMap<String, Integer>();
   result.put("a", a);
   result.put("b", b);
   return result;
}

/** Use a object to return two values */

public MyBean methodReturningTwoValues()
{
   int a = getA();
   String b = getB();
   return new MyBean(a, b);
} 

written by objects \\ tags: