Collections: binarySearch(List list, T key)
/*
Output:
Sorted list: [length: 7]
[B, H, H, L, M, M, R]
Found M @ 5
Didn't find J @ -4
* */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MainClass {
public static void main(String args[]) {
String simpsons[] = { "B", "H", "L", "M", "H", "M", "R" };
List list = new ArrayList(Arrays.asList(simpsons));
// Ensure list sorted
Collections.sort(list);
System.out.println("Sorted list: [length: " + list.size() + "]");
System.out.println(list);
// Search for element in list
int index = Collections.binarySearch(list, "M");
System.out.println("Found M @ " + index);
// Search for element not in list
index = Collections.binarySearch(list, "J");
System.out.println("Didn't find J @ " + index);
}
}
Related examples in the same category
| 1. | Collections.EMPTY_LIST | | |
| 2. | Collections.EMPTY_MAP | | |
| 3. | Collections.EMPTY_SET | | |
| 4. | Collections: comparator() | | |
| 5. | Collections: copy(List dest, List src) | | |
| 6. | Collections: emptyList() | | |
| 7. | Collections: emptyMap() | | |
| 8. | Collections: emptySet() | | |
| 9. | Collections: enumeration(Collection c) | | |
| 10. | Collections: fill(List super T> list, R obj) | | |
| 11. | Collections: list(Enumeration e) | | |
| 12. | Collections: max(Collection < ? extends T > coll) | | |
| 13. | Collections: min(Collection < ? extends T > coll) | | |
| 14. | Collections: nCopies(int n, Object o) | | |
| 15. | Collections: reverse(List> list) | | |
| 16. | Collections: reverseOrder() | | |
| 17. | Collections: replaceAll(List list, T oldVal, T newVal) | | |
| 18. | Collections: rotate(List> list, int distance) | | |
| 19. | Collections: shuffle(List < ? > list,Random rnd) | | |
| 20. | Collections: singleton(T o) | | |
| 21. | Collections: singletonList(T o) | | |
| 22. | Collections: singletonMap(T key, R value) | | |
| 23. | Collections: sort(List list) | | |
| 24. | Collections: sort(List < T > list, Comparator < ? super T > c) | | |
| 25. | Collections: swap(List> list, int i, int j) | | |
| 26. | Collections: synchronizedCollection(Collection c) | | |
| 27. | Collections: synchronizedList(List list) | | |
| 28. | Collections: synchronizedMap(Map m) | | |
| 29. | Collections: synchronizedSet(Set s) | | |
| 30. | Collections: synchronizedSet(SortedSet s) | | |
| 31. | Collections: synchronizedSortedMap(SortedMap m) | | |
| 32. | Collections: unmodifiableCollection(Collection> c) | | |
| 33. | Collections: unmodifiableList(List extends T> list) | | |
| 34. | Collections: unmodifiableMap(Map m) | | |
| 35. | Collections: unmodifiableSet(Set s) | | |