Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array index operator as a method reference

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
like image 712
Ither Avatar asked Jan 09 '23 10:01

Ither


2 Answers

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.

like image 51
Daniel Avatar answered Jan 10 '23 23:01

Daniel


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;
like image 28
Jean Logeart Avatar answered Jan 10 '23 22:01

Jean Logeart