我一直在使用Java 8 lambdas来轻松地过滤集合。但是我没有找到一种简洁的方法来检索结果,将其作为同一语句中的新列表。以下是我目前为止最简洁的方法:

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = new ArrayList<>();
sourceLongList.stream().filter(l -> l > 100).forEach(targetLongList::add);

网上的示例没有回答我的问题,因为它们没有生成新的结果列表就停止了。一定有更简洁的方法。我本来希望,Stream类有toList(), toSet(),…

是否有一种方法,变量targetLongList可以直接由第三行分配?


当前回答

在Java 16中有一个新的方法Stream.toList():

List<Long> targetLongList = sourceLongList
         .stream()
         .filter(l -> l > 100)
         .toList();

其他回答

这里是常用的算盘代码

LongStream.of(1, 10, 50, 80, 100, 120, 133, 333).filter(e -> e > 100).toList();

披露:我是abacus-common的开发者。

如果有人(比如我)正在寻找处理对象而不是基本类型的方法,那么就使用mapToObj()

String ss = "An alternative way is to insert the following VM option before "
        + "the -vmargs option in the Eclipse shortcut properties(edit the "
        + "field Target inside the Shortcut tab):";

List<Character> ll = ss
                        .chars()
                        .mapToObj(c -> new Character((char) c))
                        .collect(Collectors.toList());

System.out.println("List type: " + ll.getClass());
System.out.println("Elem type: " + ll.get(0).getClass());
ll.stream().limit(50).forEach(System.out::print);

打印:

List type: class java.util.ArrayList
Elem type: class java.lang.Character
An alternative way is to insert the following VM o

一个更有效的方法(避免创建源列表和由过滤器自动开箱):

List<Long> targetLongList = LongStream.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L)
    .filter(l -> l > 100)
    .boxed()
    .collect(Collectors.toList());

如果你不使用parallel(),这也可以工作

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);

List<Long> targetLongList =  new ArrayList<Long>();

sourceLongList.stream().peek(i->targetLongList.add(i)).collect(Collectors.toList());

更新:

另一种方法是使用collections . tolist:

targetLongList = 
    sourceLongList.stream().
    filter(l -> l > 100).
    collect(Collectors.toList());

之前的解决方案:

另一种方法是使用collections . tocollection:

targetLongList = 
    sourceLongList.stream().
    filter(l -> l > 100).
    collect(Collectors.toCollection(ArrayList::new));