Java 8惯用的方法将Lambda应用于List返回另一个List?

Ale*_*x R 9 java lambda list-comprehension list java-8

将lambda应用于列表中的每个项目的最惯用机制是什么,返回由结果组成的列表?

例如:

List<Integer> listA = ... imagine some initialization code here ...

List<Integer> listB = listA.apply(a -> a * a);   // pseudo-code (there is no "apply")

/* listB now contains the square of every value in listA */
Run Code Online (Sandbox Code Playgroud)

我查看了API javadocs并查看了Apache Commons,但没有找到任何内容.

Era*_*ran 27

您可以使用Streamwith mapcollect:

listB = listA.stream()
             .map (a -> a*a)
             .collect (Collectors.toList());
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 10

要添加到@Eran的答案,我有一个帮助方法:

public static <T, R> List<R> apply(Collection<T> coll, Function<? super T, ? extends R> mapper) {
    return coll.stream().map(mapper).collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)

可以用作:

List<Integer> listB = apply(listA, a -> a * a);
Run Code Online (Sandbox Code Playgroud)

(注意:将需要Java 1.8或更高版本.)

  • 这很适合作为集合的默认方法. (2认同)

rol*_*lfl 5

最标准的方法是在最后收集它们:

List<Integer> listA = ... imagine some initialization code here ...
List<String> listB = listA.stream()
                         .map(a -> a.toString())
                         .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

请注意map函数如何引入一个转换,在本例中为Integer转换为String,返回的列表属于该List<String>类型.转换由映射执行,List由收集器生成.