簡體   English   中英

在Stream.map()中將Consumer轉換為Runnable

[英]Convert Consumer into Runnable inside Stream.map()

我正在嘗試將Consumer轉換為Runnable 下面的代碼不會生成Eclipse IDE中任何編譯器錯誤。

Consumer<Object> consumer;
Runnable runnable;
Object value;

...
runnable = () -> consumer.accept(value);

以下代碼在Eclipse IDE中生成編譯器錯誤。

ArrayList<Consumer<Object>> list;
Object value;

...

list.
   stream().
   map(consumer -> () -> consumer.accept(value));

錯誤是:

Type mismatch: Can not convert from Stream<Object> to <unknown>.
The target type of this expression must be a functional interface.

如何幫助編譯器將Consumer轉換為Runnable

以下代碼修復了該問題,但非常詳細。

map(consumer -> (Runnable) (() -> consumer.accept(value)));

有沒有更簡潔的方法來做到這一點? 我知道我可以創建一個接受Consumer並返回Runnable的靜態方法,但我不認為這更簡潔。

如果您考慮表達式,則錯誤消息是正常的:

list.stream().map(consumer -> () -> consumer.accept(value))
                              ^--------------------------^
                                what is the type of that?

問題是編譯器無法確定表達式() -> consumer.accept(value)的目標類型。 它當然可以是Runnable ,但也可以是MyAwesomeInterface聲明:

@FunctionalInterface
interface MyAwesomeInterface { void foo(); }

實際上,它可以符合任何聲明函數方法的函數接口,該函數方法不帶參數並且不返回任何值。 因此,這會導致編譯錯誤。

使用以下命令在Runnable顯式存儲lambda表達式時沒有錯誤:

Runnable runnable = () -> consumer.accept(value);

因為,然后編譯器知道該lambda的目標類型是Runnable


當你考慮時,問題更加模糊:

List<Runnable> runnables = list.stream()
                               .map(consumer -> () -> consumer.accept(value))
                               .collect(Collectors.toList());

有人可能會爭辯說,編譯器可能能夠將該表達式的目標類型推斷為Runnable因為我們將其收集到Runnable列表中。 但是, 它沒有 ,你必須幫助編譯器一點點,並明確告訴編譯器Stream元素是Runnable

List<Runnable> runnables = list.stream()
                               .<Runnable> map(consumer -> () -> consumer.accept(value))
                               .collect(Collectors.toList());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM