2 回答
TA貢獻1850條經驗 獲得超11個贊
您調用的方法forEach不是Stream::forEach方法,而是Map::forEach方法,因為您在 的返回值(collect(...)即Map.?該方法的一個特點Map::forEach是它采用BiConsumer, 而不是Consumer。流forEach永遠不會接受帶有兩個參數的 lambda!
因此,您只調用一個終端操作,即collect流上的操作。在那之后,您再也沒有對流執行任何操作(您開始使用返回的Map),這就是IllegalStateExcepton拋出 no 的原因。
要實際在同一流上調用兩個終端操作,您需要首先將流放入變量中:
List<String> list = Arrays.asList("ant", "bird", "chimpanzee", "dolphin");
Stream<String> stream = list.stream(); // you need this extra variable.
stream.collect(Collectors.groupingBy(String::length));
stream.forEach((a) -> System.out.println(a)); // this will throw an exception, as expected
TA貢獻1869條經驗 獲得超4個贊
生成的流list.stream()由該操作消耗collect。但作為分組結果的操作是Map<Integer, List<String>>根據字符串的大小生成的。
thenforEach調用Map由 生成的this 條目,因此后者collect不會拋出異常。IllegalStateException
添加回答
舉報
