This examples 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.example.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<>();
monthList.addAll(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
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020