Can someone tell me how i should use consumers to reach the same output, because this doesn't work ?
String names = "John Alex Peter";
String[] namesSplitted = names.split(" ");
for (String s : namesSplitted) {
System.out.println(s);
}
Consumer<String> cons = x -> System.out.println(x.split(" "));
cons.accept(names);
A Consumer
receives input and processes it (i.e. "consumes" it).
A Consumer<String>
consumes one String
at a time.
In your code sample, the Consumer
is System.out.println
.
You can create a Stream<String>
from splitting the input String
, and pass all the elements of this Stream
to the Consumer<String>
by calling forEach()
:
Consumer<String> cons = System.out::println;
Arrays.stream(names.split(" ")).forEach(cons);
Of course there's no need to separate this snippet into two lines:
Arrays.stream(names.split(" ")).forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With