【发布时间】:2017-07-14 08:18:10
【问题描述】:
在某些情况下,使用 Java 8 Stream 会使我重复执行某些操作,如果不使用 Stream 可以避免这种情况,但我认为问题不在于流,而在于我。
一些例子:
private class Item {
String id;
List<String> strings;
}
// This method, filters only the Items that have the strToFind, and
// then maps it to a new string, that has the id and the str found
private void doIt(List<Item> items, String strToFind) {
items.stream().filter(item -> {
return item.strings.stream().anyMatch(str -> this.operation(str, strToFind));
}).map(item -> {
return item.id + "-" + item.strings.stream()
.filter(str -> this.operation(str, strToFind)).findAny().get();
});
}
// This operation can have a lot of overhead, therefore
// it would be really bad to apply it twice
private boolean operation(String str, String strToFind) {
return str.equals(strToFind);
}
如您所见,函数operation 被每个项目调用两次,我不希望这样。我首先想到的是直接映射并在找不到时返回“null”,然后过滤空值,但如果这样做,我将丢失对 Item 的引用,因此无法使用 id。
【问题讨论】:
-
我猜有一个更聪明的选择,但就像你建议的那样,在
map-then-filter之后出现了使用reduce有选择地转换并推送到新列表的想法。 -
在这种情况下,
item.strings.stream().filter(str -> this.operation(str, strToFind)).findAny().get()可以被strToFind替换,但我猜operation实际上并没有这样实现? -
@JornVernee 是的,我放了一个
equals来代表一个操作,但这可能是不同的东西。我没有放原始代码,因为代码很多.. -
我发现不用水平滚动阅读这篇文章要容易得多,但如果您反对,请随时恢复我的编辑。
-
@DavidConrad 没问题!我也觉得更容易:)
标签: java performance java-stream