Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Consumer split by Line

Tags:

java

java-8

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);
like image 974
Spongi Avatar asked Feb 05 '23 05:02

Spongi


1 Answers

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);
like image 76
Eran Avatar answered Feb 06 '23 18:02

Eran