4 回答

TA貢獻1877條經驗 獲得超6個贊
理想情況下,您不應該改變外部列表,而是可以使用Collectors.toList()將其收集到列表中:
List<String> list = stream.peek(System.out::println)
.filter(p1.or(p2))
.collect(Collectors.toList()); // triggers the evaluation of the stream
System.out.println("Size = "+list.size());
在您的示例中,僅當終端操作像
allMatch()
anyMatch()
noneMatch()
collect()
count()
forEach()
min()
max()
reduce()

TA貢獻1772條經驗 獲得超8個贊
由于您還沒有完成流操作,即peek是一個中間操作。您必須使用終端操作才能繼續執行。
建議:改為使用終端操作執行此類操作,例如collect
List<String> list = stream.peek(System.out::println)
.filter(p1.or(p2))
.collect(Collectors.toList());
另外:添加一個peek帖子filter來觀察值在觀察中可能有點棘手,如下代碼
List<String> list = stream.peek(System.out::println)
.filter(p1.or(p2))
.peek(System.out::println) // addition
.collect(Collectors.toList());
輸出看起來像:
one
two
two // filtered in
three
three // filtered in
four
five

TA貢獻1752條經驗 獲得超4個贊
溪流是懶惰的。您可以調用終端操作,例如forEach
:
stream.peek(System.out::println) .filter(p1.or(p2)) .forEach(list::add);
如果您想peek
用作調試目的的中間操作,那么您必須在之后調用終端操作:
stream.peek(System.out::println) .filter(p1.or(p2)) .peek(list::add); .<any terminal operation here>();
順便說一句,如果您只想將所有過濾后的值存儲在一個列表中,那么最好使用collect(toList())
.

TA貢獻1877條經驗 獲得超1個贊
您所做的一切filter
都是peek
設置一系列操作以應用于流。您實際上還沒有使它們中的任何一個運行。您必須添加一個終端操作,例如count
. (另一個答案建議使用forEach
添加到列表中,但我認為您專門嘗試使用中間操作peek
。)
添加回答
舉報