数组索引运算符作为方法引用

时间:2015-05-08 17:46:29

标签: java lambda java-8

如果有一个String数组,我想要第一个元素。可以在Java 8中为此编写方法参考吗?例如

String[] strings = new String[] {"aa","bb","cc","dd"};
Function<String[], String> first = Array::[0];    // this should be "aa"

我发现的是

Function<String[], String> first = (strings -> strings[0]);

有效,但我想知道它是否可行。提前谢谢。

编辑:好的,似乎不可能。奖金问题:有可能使用List<String>吗?类似的东西:

List<String> strings = Arrays.asList("aa","bb","cc","dd");
Function<List<String>, String> first = List::get(0); // this don't work, obviously

3 个答案:

答案 0 :(得分:3)

您可以创建自己的:

public class MyArrayUtils {
    public static <T> T getFirst(T[] a) {
        return a[0];
    }
}

Function<String[], String> first = MyArrayUtils::<String>getFirst;

答案 1 :(得分:3)

阵列没有这样的功能。但是,streams do have such functionarrays are convertible to streams

Function<Stream<String>,Optional<String>> f = Stream::findFirst;
String[] data = new String[] {"aa","bb","cc","dd"};
Optional<String> res = f.apply(Arrays.stream(data));
System.out.println(res.get());

Demo.

答案 2 :(得分:3)

我能搞清楚的最近的事情。

 // 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);

不完全是干净透明的衬垫。

最佳答案是array -> array[0]list -> list.get(0)这些是最清晰,最简洁的。