June 10, 2016

Java Streams in Java 8

java.util.stream.Stream

Stream is a new feature in Java 8 that brings a lot of operation for Collections. Here I will present the most important, but for a complete list see the Java API.

In the below examples I will use a List of Strings.

List<String> strings = Arrays.asList(new String[] { "Alf", "Bo", "Doo", "Core", "Adam", "Nisse" });

filter()

strings.stream().filter(s -> s.contains("o")).forEach(System.out::println);

map()

The map() method converts each element into another object via the given function.

strings.stream().map(s -> s.toUpperCase()).forEach(System.out::println);

sorted()

strings.stream().sorted((s1, s2) -> s1.compareTo(s2)).forEach(System.out::println);

collect()

Creates a new Collection.

List<String> result = strings.stream().sorted().collect(Collectors.toList());

match()

Returns matched elements in Collections.

boolean anyMatch = strings.stream().anyMatch(s -> s.startsWith("A"));
System.out.println("anyMatch: " + anyMatch);

boolean allMatch = strings.stream().allMatch(s -> s.startsWith("A"));
System.out.println("allMatch: " + allMatch);

boolean noneMatch = strings.stream().noneMatch(s -> s.startsWith("A"));
System.out.println("noneMatch: " + noneMatch);

count()

long noItems = strings.stream().count();
System.out.println("noItems: " + noItems);

reduce()

Collaps the entire Collections to single element.

Optional<String> reduce = strings.stream().reduce((s1, s2) -> s1 + ", " + s2);
System.out.println("reduce: "+ reduce.get());

No comments: