Java 8 Consumer section on line

Can someone tell me how should I use consumers to achieve the same output, because it does not 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);
+4
source share
3 answers

A Consumerreceives the input and processes it (ie, "consumes" it).

A Consumer<String>consumes one Stringat a time.

In the sample code Consumeris System.out.println.

You can create Stream<String>to separate the input Stringand pass all the elements of this Streaminto Consumer<String>by calling forEach():

Consumer<String> cons = System.out::println;
Arrays.stream(names.split(" ")).forEach(cons);

Of course, there is no need to separate this fragment into two lines:

Arrays.stream(names.split(" ")).forEach(System.out::println);
+4
source

Consumer String, String[].

Pattern # splitAsStream, , Consumer String, :

Pattern.compile(" ").splitAsStream(names).forEach(System.out::println);

String # replaceAll String # join, :

Consumer<String> cons =System.out::println;

cons.accept(names.replaceAll(" ","\n"));

//OR
cons.accept(String.join("\n", names.split(" ")));
+4

Convert an array to a stream and then use the user.

public static void main(String args[]){

    String names = "John Alex Peter";
    String[] namesSplitted = names.split(" ");

    for (String s : namesSplitted) {
        System.out.println(s);
    }

   Consumer<String> printConsumer =  System.out::println;
   Arrays.stream(names.split(" ")).forEach( printConsumer);

    // OR Simply
    Arrays.stream(names.split(" ")).forEach( System.out::println);

}
0
source

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


All Articles