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"を返し、その後nullをフィルタリングすることでしたが、私がそうすると、Itemへの参照が失われ、idを使用できなくなります。
私は、よりきめ細かなオプションがあると思いますが、 'map'-then-' filter'の直後に 'reduce'を使って選択的に変換して新しいリストにプッシュするという考えが示唆されました。 – user650881
この場合、 'item.strings.stream()。filter(str - > this.operation(str、strToFind))。findAny()。get()'は 'strToFind'で置き換えることができますが、操作は実際にはそのように実装されていませんか? –
@ JornVernee右、演算を表すために 'equals'を置いていますが、それは違うものかもしれません。 –