How do I search collection elements?

This code example use the Collections.binarySearch() to search an specified object inside a specified collections. Prior to calling the binarySearch() method we need to sort the elements of the collection. If the object is not sorted according to their natural order the search result will be undefined.

package org.kodejava.util;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Collections;
import java.text.DateFormatSymbols;

public class CollectionSearch {
    public static void main(String[] args) {
        DateFormatSymbols dfs = new DateFormatSymbols();

        LinkedList<String> monthList =
                new LinkedList<>(Arrays.asList(dfs.getMonths()));

        // Sort the collection elements
        Collections.sort(monthList);
        System.out.println("Months = " + monthList);

        // Get the position of November inside the monthList. It returns a positive
        // value if the item found in the monthList.
        int index = Collections.binarySearch(monthList, "November");
        if (index > 0) {
            System.out.println("Found at index = " + index);
            System.out.println("Month = " + monthList.get(index));
        }
    }
}

The output of the code snippet above is below.

Months = [, April, August, December, February, January, July, June, March, May, November, October, September]
Found at index = 10
Month = November

How do I rotate elements of a collection?

This example demonstrate how to rotate the elements of a collection object. We can use the java.util.Collections class and call the rotate() method with the collection to rotate and the distance as the parameters.

package org.kodejava.util;

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

public class CollectionRotate {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();

        // Add some items into the collection
        for (int i = 0; i < 25; i++) {
            numbers.add(i);
        }

        // Print the collection items        
        System.out.println(Arrays.toString(numbers.toArray()));

        // Rotates the elements in the collection by the 10.
        Collections.rotate(numbers, 10);

        // Print the rotated collection items
        System.out.println(Arrays.toString(numbers.toArray()));
    }
}

Here is the program result:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

How do I sort strings using Collator class?

In this example we demonstrate how to use the java.text.Collator class to sort strings in language-specific order. Using the java.text.Collator class makes the string not just sorted by the ASCII code of their characters, but it will follow the language natural order of the characters.

package org.kodejava.text;

import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.text.Collator;

public class StringShortWithCollator {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Guava");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Mango");
        fruits.add("Apple");

        // Define a collator for US English.
        Collator collator = Collator.getInstance(Locale.US);

        // Sort the list base on the collator
        fruits.sort(collator);

        for (String fruit : fruits) {
            System.out.println("Fruit = " + fruit);
        }
    }
}

The result of the code snippet above are:

Fruit = Apple
Fruit = Banana
Fruit = Guava
Fruit = Mango
Fruit = Orange

How do I sort items of an ArrayList?

This example shows you how we can sort items of an ArrayList using the Collections.sort() method. Beside accepting the list object to be sorted we can also pass a Comparator implementation to define the sorting behaviour such as sorting in descending or ascending order.

package org.kodejava.util;

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

public class ArrayListSortExample {
    public static void main(String[] args) {
        /*
         * Create a collections of colours
         */
        List<String> colours = new ArrayList<>();
        colours.add("red");
        colours.add("green");
        colours.add("blue");
        colours.add("yellow");
        colours.add("cyan");
        colours.add("white");
        colours.add("black");

        /*
         * We can sort items of a list using the Collections.sort() method.
         * We can also reverse the order of the sorting by passing the
         * Collections.reverseOrder() comparator.
         */
        Collections.sort(colours);
        System.out.println(Arrays.toString(colours.toArray()));

        colours.sort(Collections.reverseOrder());
        System.out.println(Arrays.toString(colours.toArray()));
    }
}

The code will output:

[black, blue, cyan, green, red, white, yellow]
[yellow, white, red, green, cyan, blue, black]

How do I sort array values in descending order?

Here you will find an example on how to sort the values of an array in ascending or descending order.

package org.kodejava.util;

import java.util.Arrays;
import java.util.Collections;

public class SortArrayWithOrder {
    public static void main(String[] args) {
        Integer[] points = new Integer[5];
        points[0] = 94;
        points[1] = 53;
        points[2] = 70;
        points[3] = 44;
        points[4] = 64;
        System.out.println("Original  : " + Arrays.toString(points));

        // Sort the points array, the default order is in ascending order.
        // [44, 53, 64, 70, 94]
        Arrays.sort(points);
        System.out.println("Ascending : " + Arrays.toString(points));

        // Sort the points array in descending order.
        // [94, 70, 64, 53, 44]
        Arrays.sort(points, Collections.reverseOrder());
        System.out.println("Descending: " + Arrays.toString(points));
    }
}

The result of the code snippet above are:

Original  : [94, 53, 70, 44, 64]
Ascending : [44, 53, 64, 70, 94]
Descending: [94, 70, 64, 53, 44]