If have an array of String
and I want the first element. It is possible to write a method reference for this in Java 8? For example
String[] strings = new String[] {"aa","bb","cc","dd"};
Function<String[], String> first = Array::[0]; // this should be "aa"
What I found is that
Function<String[], String> first = (strings -> strings[0]);
works, but I want to know if it is posible. Thanks in advance.
Edit: Ok, seems it is not possible. Bonus question: it is possible with a List<String>
, then? Something like:
List<String> strings = Arrays.asList("aa","bb","cc","dd");
Function<List<String>, String> first = List::get(0); // this don't work, obviously
Closest thing I could figure out.
// For an array,
final Function<String[], String> firstArr =
((Function<Optional<String>,String>)Optional::get)
.<Stream<String>>compose(Stream::findFirst)
.compose(Arrays::stream);
// For a collection
final Function<List<String>, String> firstCol =
((Function<Optional<String>,String>)Optional::get)
.<Stream<String>>compose(Stream::findFirst)
.compose(Collection::stream);
Not exactly a clean and clear one liner.
The best answer is array -> array[0]
and list -> list.get(0)
These are the clearest and most concise.
You can create your own:
public class MyArrayUtils {
public static <T> T getFirst(T[] a) {
return a[0];
}
}
Function<String[], String> first = MyArrayUtils::<String>getFirst;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With