在Java 8中从java.util.stream.Stream中检索列表

497

我在尝试使用Java 8的lambda表达式来轻松过滤集合。但是我没有找到一种简洁的方式来在同一语句中将结果作为新列表检索出来。以下是目前我最简洁的方法:

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


7
如果您之后不需要sourceLongList,可以使用Collection.removeIf(…)进行方便的操作。请注意,该方法可以移除满足特定条件的元素。 - Holger
3
这个怎么样?List<Long> targetLongList = sourceLongList.stream().collect(Collectors.toList()); - leeyuiwah
15个回答

0

如果有人(像我一样)正在寻找处理对象而不是原始类型的方法,那么可以使用 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

0

这里是 abacus-common 的代码

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

声明:我是abacus-common的开发者。


1
LongStream类中没有找到任何toList方法。你能运行这段代码吗? - Vaneet Kataria
@VaneetKataria 请尝试在AbacusUtil中使用com.landawn.abacus.util.stream.LongStreamLongStreamEx - user_3380739

0
你可以将代码重写如下:
List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = sourceLongList.stream().filter(l -> l > 100).collect(Collectors.toList());

感谢您的回复。但是,请解释一下您所做的更改,以及它与问题有何关系。 - B--rian
首先,我将我的ArrayList转换为流,并使用过滤器筛选出所需数据。最后,我使用Java 8流的collect方法将数据收集到名为targetLongList的新列表中。 - Pratik Pawar

0
String joined = 
                Stream.of(isRead?"read":"", isFlagged?"flagged":"", isActionRequired?"action":"", isHide?"hide":"")
                      .filter(s -> s != null && !s.isEmpty())
                      .collect(Collectors.joining(","));

-3

如果您不使用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());

我不喜欢collect()只是用来驱动流,以便在每个项目上调用peek()钩子。终端操作的结果被丢弃。 - Daniel K.
调用 collect 方法却不保存返回值是非常奇怪的。在这种情况下,您可以使用 forEach 方法代替。但这仍然是一个不好的解决方案。 - Lii
1
以这种方式使用peek()是一种反模式。 - Grzegorz Piwowarek
根据Stream Java文档,peek方法仅用于调试目的。它不应用于除调试之外的任何处理。 - Vaneet Kataria

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接