-
Enhancement
-
Resolution: Unresolved
-
P4
-
None
-
None
-
generic
-
generic
A DESCRIPTION OF THE PROBLEM :
The current binarySearch implementations in java.util.Arrays require direct comparability between array elements and the search key. However, in many real-world scenarios, data structures contain objects where the search should be based on a derived key rather than the object itself.
To address this, the proposed methods provide:
1. A binarySearch method that extracts keys using a Function<? super T, Comparable<? super K>> and performs a binary search based on the natural ordering of the extracted keys.
2. A binarySearch method that allows specifying a Comparator<? super K> for cases where a custom ordering is needed.
Proposed Method Signatures:
public static <T, K> int binarySearch(T[] array, K key, Function<? super T, Comparable<? super K>> fn)
public static <T, K> int binarySearch(T[] array, K key, Function<? super T, K> fn, Comparator<? super K> c)
Use Cases:
1. Searching in an Array of Objects by a Specific Field
record Person(String name, int age) {}
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
};
Arrays.sort(people, Comparator.comparingInt(Person::age));
int index = Arrays.binarySearch(people, 30, Person::age);
2. Searching with a Custom Comparator
int index = Arrays.binarySearch(people, "Alice", Person::name, String.CASE_INSENSITIVE_ORDER);
The current binarySearch implementations in java.util.Arrays require direct comparability between array elements and the search key. However, in many real-world scenarios, data structures contain objects where the search should be based on a derived key rather than the object itself.
To address this, the proposed methods provide:
1. A binarySearch method that extracts keys using a Function<? super T, Comparable<? super K>> and performs a binary search based on the natural ordering of the extracted keys.
2. A binarySearch method that allows specifying a Comparator<? super K> for cases where a custom ordering is needed.
Proposed Method Signatures:
public static <T, K> int binarySearch(T[] array, K key, Function<? super T, Comparable<? super K>> fn)
public static <T, K> int binarySearch(T[] array, K key, Function<? super T, K> fn, Comparator<? super K> c)
Use Cases:
1. Searching in an Array of Objects by a Specific Field
record Person(String name, int age) {}
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
};
Arrays.sort(people, Comparator.comparingInt(Person::age));
int index = Arrays.binarySearch(people, 30, Person::age);
2. Searching with a Custom Comparator
int index = Arrays.binarySearch(people, "Alice", Person::name, String.CASE_INSENSITIVE_ORDER);