/java/

Java8 – Stream simple example

2015-01-14 20:25:45

Two simple way to start work with stream

Arrays.asList("dog", "cat", "human", "bird", "turtle")
        .stream()
        .forEach(System.out::println);
Stream.of("dog", "cat", "human", "bird", "turtle")
        .forEach(System.out::println);

What we can do more

List

<string> animals = Arrays.asList("dog", "cat", "human", "bird", "turtle");

count item

System.out.println(animals.stream().count());

filter

animals.stream().filter(a -&gt; a.equals("dog")).forEach(System.out::println);
animals.stream().filter(a -&gt; a.startsWith("d")).forEach(System.out::println);
animals.stream().filter(a -&gt; a.startsWith("h")).forEach(System.out::println);

mapping

animals.stream().map(String::toLowerCase).forEach(System.out::println);
animals.stream().map(String::toUpperCase).forEach(System.out::println);
animals.stream().map(Main::mapper).forEach(System.out::println);

private static Object mapper(String s) {
    return "Animal: " + s;
}