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 search specific value in an array?

package org.kodejava.util;

import java.util.Arrays;

public class ArraySearchExample {
    public static void main(String[] args) {
        // We create an array of ints where the search will be done.
        int[] items = {9, 5, 14, 6, 11, 28, 9, 16, 37, 3, 2};

        // The Arrays.binarySearch() require us to sort the array
        // items before we call the method. We can utilize the
        // Arrays.sort() method to do this. If we did not sort the
        // array the result will be undefined, the search process
        // will return a negative result.
        Arrays.sort(items);

        // To search we use Arrays.binarySearch() methods which accept
        // parameters of any array type. To search we passed the array
        // to be searched and the key to be searched for.
        //
        // When the search item exist more than one in the array, this
        // method gives no guarantee which one will be returned.
        int needle = 9;
        int index = Arrays.binarySearch(items, needle);

        // Print out where the 9 number is located in the array.
        System.out.println("Items: " + Arrays.toString(items));
        System.out.println("Item " + needle + " is at index " + index);
    }
}

There result of the code snippet:

Items: [2, 3, 5, 6, 9, 9, 11, 14, 16, 28, 37]
Item 9 is at index 5