将循环(while和for)转换为流 [英] Convert an loop (while and for) to stream
问题描述
我已经开始使用Java 8,并尝试将代码中的某些循环和旧语法转换为lambda和流.
I have started working with Java 8 and trying to convert some loops and old syntax in my code to lambdas and streams.
因此,例如,我试图在while和for循环中将其转换为流,但我做得不正确:
So for example, I'm trying to convert this while and for loop to stream, but I'm not getting it right:
List<String> list = new ArrayList<>();
if (!oldList.isEmpty()) {// old is a List<String>
Iterator<String> itr = oldList.iterator();
while (itr.hasNext()) {
String line = (String) itr.next();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (line.startsWith(entry.getKey())) {
String newline = line.replace(entry.getKey(),entry.getValue());
list.add(newline);
}
}
}
}
我想知道是否可以将上述示例转换为单个流,其中for循环中有一个while循环.
I wanted to know if it's possible to convert the above example to a single stream where there is a while loop inside of a for loop.
推荐答案
如上所述,在此处使用流并不会真正增加价值,因为它使代码更难于阅读/理解.我知道您正在做更多的学习活动.话虽这么说,做这样的事情是一种功能性更强的方法,因为它没有从流本身内部添加到列表中的副作用:
As was stated above, using streams here doesn't really add value since it makes the code harder to read/understand. I get that you're doing it more as a learning exercise. That being said, doing something like this is a slightly more functional-style approach as it doesn't have a side effect of adding to the list from within the stream itself:
list = oldList.stream().flatMap(line->
map.entrySet().stream()
.filter(e->line.startsWith(e.getKey()))
.map(filteredEntry->line.replace(filteredEntry.getKey(),filteredEntry.getValue()))
).collect(Collectors.toList());
这篇关于将循环(while和for)转换为流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!