简体   繁体   English

传递lambda函数作为参数

[英]Passing a lambda function as a parameter

I'm trying to create an equivalent to Javascript's Array#map in Java. 我正在尝试用Java创建一个等效的Javascript的Array#map #map。

I have been able to do it with 我已经能够做到这一点

ArrayList<String> data = myList.stream().map(e -> {
    return "test "+e;
}).collect(Collectors.toCollection(ArrayList::new));

Here, myList is the initial ArrayList and data is the resulting ArrayList . 这里, myList是初始的ArrayListdata是生成的ArrayList

However, I find it very tedious to do that every time. 但是,我发现每次这样做都非常繁琐。

So I tried to create a generic function that would make my life easier : 所以我尝试创建一个让我的生活更轻松的通用函数:

public static ArrayList<?> map(ArrayList<?> list, Function<? super Object,?> callback){
    return list.stream().map(callback).collect(Collectors.toCollection(ArrayList::new));
}

And then calling it with: 然后调用它:

ArrayList<String> data = DEF.map(myList,e -> {
    return "test "+e;
});

But I get the error 但是我得到了错误

[Java] The method map(ArrayList, Function) in the type DEF is not applicable for the arguments (List, ( e) -> {}) [Java] DEF类型中的方法map(ArrayList,Function)不适用于参数(List,(e) - > {})

How can I edit my generic function to accept the lambda I'm using? 如何编辑我的通用函数以接受我正在使用的lambda?

You should define your method with two generic type parameters - the element type of the source list, and the element type of the target list : 您应该使用两个泛型类型参数定义您的方法 - 源列表的元素类型和目标列表的元素类型:

public static <S,T> ArrayList<T> map(ArrayList<S> list, Function<S,T> callback)
{
    return list.stream().map(callback).collect(Collectors.toCollection(ArrayList::new));
}

It would also be better to use the List interface instead of ArrayList : 使用List接口而不是ArrayList也会更好:

public static <S,T> List<T> map(List<S> list, Function<S,T> callback)
{
    return list.stream().map(callback).collect(Collectors.toList());
}

Example of usage: 用法示例:

List<Integer> myList = Arrays.asList (1,2,3,4);
List<String> datai = map(myList ,e -> "test " + e);

Output: 输出:

[test 1, test 2, test 3, test 4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM