Nov 27

Sometimes we need to shuffle the oder of elements in a list or array, like shuffling a deck of cards. The Collections utility class has a shuffle() method that achieves this for List’s, but what about arrays. There is no corresponding shuffle() method in the Arrays class, surely we don’t need to loop through the array.

Turns out the solution is very simple. We can just use the same method we use for shuffling lists after first creating a List representation of our array using Arrays.asList()

String[] array = {"A", "B", "C", "D", "E"};
Collections.shuffle(Arrays.asList(array));
System.out.println(Arrays.toString(array));

written by objects \\ tags: , , , ,

Oct 14

Sometimes an api will return you an Enumeration but what you want is a List. The Collections class has a utility method that creates a List containing the elements from the Enumeration.

Enumeration en = someMethodThatReturnsEnumeration();
List list = Collections.list(en);

written by objects \\ tags: , ,

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: , , , , ,