我有一些情况下,使用Java 8 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'来选择性地转换并推送到一个新列表。 – user650881
在这种情况下,'item.strings.stream()。filter(str - > this.operation(str,strToFind))。findAny()。get()'可以被'strToFind'替换,但我猜'操作'不是那样实际执行的? –
@JornVernee对,我把一个'equals'代表一个操作,但这可能是不同的东西。我没有把原来的代码,因为是很多代码.. –