Convert user to Runnable inside Stream.map ()

I am trying to convert Consumerto Runnable. The following code does not generate compiler errors.

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

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

The following code generates a compiler error in the Eclipse IDE.

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

...

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

Errors:

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

How can I help the compiler convert Consumerto Runnable?

The following code fixes the problem, but very verbose.

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

Is there a more concise way to do this? I know that I can create a static method that accepts Consumerand returns Runnable, but I do not think about it more concisely.

+4
source share
1 answer

, :

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

, () -> consumer.accept(value). , , Runnable, MyAwesomeInterface :

@FunctionalInterface
interface MyAwesomeInterface { void foo(); }

, , , . , .

- Runnable :

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

, 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());
+10

Source: https://habr.com/ru/post/1629429/


All Articles