Friday, March 23, 2018

JShell, Collectors, Stream, stream, map, filter and forEach

jshell> String[] names = {"Bill", "Sue", "Joey", "Samantha", "Theresa"};
names ==> String[5] { "Bill", "Sue", "Joey", "Samantha", "Theresa" }

jshell> Stream.of(names).forEach(p -> System.out.println(p.toUpperCase()))
BILL
SUE
JOEY
SAMANTHA
THERESA

jshell> 
jshell> List<String> people = List.of("Bill", "Sue", "Joey", "Samantha", "Theresa");
people ==> [Bill, Sue, Joey, Samantha, Theresa]

jshell> people.stream().map(String::toUpperCase).forEach(System.out::println)
BILL
SUE
JOEY
SAMANTHA
THERESA

jshell> people.stream().filter(p -> p.equals("Joey")).forEach(System.out::println)
Joey

jshell> 
jshell> List<String> people = List.of("Bill", "Sue", "Jenny", "Sarah", "Tim", "Brian");
people ==> [Bill, Sue, Jenny, Sarah, Tim, Brian]

jshell> people.stream().filter(p -> p.substring(0,1).equals("B"))
    .forEach(System.out::println) Bill Brian jshell> List<String> results = people.stream(). ...> filter(p -> p.substring(0,1).equals("B")). ...> collect(Collectors.toList()) results ==> [Bill, Brian] jshell>