在Java中,有什么比stream()。forEach()更有效的方法,但仍使用流操作?

问题描述 投票:0回答:1

例如,我有一个字符串列表(可能超过5000,并且我需要效率!)。我想对它们每个应用相同的操作,例如分裂或其他。

现在我使用

List<String> a = ....;
a.stream().forEach(x->{
    //some code here...
    //maybe a split?
    String[] ss=x.split("...");
    Arrays.stream(ss).forEach(y->{...});
});

我知道它目前效率很低,但是如何改善呢?顺便说一句,parallelStream不应该使用!

非常感谢您的帮助!

java algorithm performance stream
1个回答
0
投票

您可以使用map函数,将字符串映射到所需的值,然后遍历它们

a.stream().map(s -> s.split("...")).forEach(split -> {});

或者,您可以过滤它们,

a.stream().map(s -> s.split("...")).filter(split -> split.length > 0);

或者您可以收集它们,

a.stream().map(s -> s.split("...")).filter(split -> split.length > 0).collect(Collectors.toList());

您可以使用流执行许多操作,这些只是一些示例。

© www.soinside.com 2019 - 2024. All rights reserved.