Streams in Java
July 30, 2020
Here's a few examples on how Streams can be used in Java.
package uk.co.drumcoder; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class Test { public static void main(String[] args) { final List<Integer> testList = Arrays.asList(10, 7, 14, 1, 3, 3, 14); // stream of list final Stream<Integer> testStream = testList.stream(); System.out.println("Stream"); testStream.forEach((i) -> System.out.println(i)); // ordered stream final Stream<Integer> sortedStream = testList.stream().sorted(); System.out.println("Sorted Stream"); sortedStream.forEach((i) -> System.out.println(i)); // Find first item final Optional<Integer> firstItem = testList.stream().findFirst(); if (firstItem.isPresent()) { System.out.println("First Item"); System.out.println(firstItem.get()); } // reversed stream final Stream<Integer> reversedStream = testList.stream().sorted(Collections.reverseOrder()); System.out.println("Reverse Sorted"); reversedStream.forEach(System.out::println); // doubled stream final Stream<Integer> doubledStream = testList.stream().sorted().map(e -> e * 2); System.out.println("Doubled Stream"); doubledStream.forEach(System.out::println); // sum numbers in a stream using reduce final int startValue = 0; final Integer sum1 = testList.stream().reduce(startValue, (a, b) -> a + b); System.out.println("Sum of integers (reduce)"); System.out.println(sum1); // sum numbers in stream using collect final Integer sum2 = testList.stream().collect(Collectors.summingInt(Integer::intValue)); System.out.println("Sum of integers (collect)"); System.out.println(sum2); // sum numbers using sum final Integer sum3 = testList.stream().mapToInt(Integer::intValue).sum(); System.out.println("Sum of integers (sum)"); System.out.println(sum3); // create list from stream final Stream<Integer> listStream = testList.stream().sorted(); final List<Integer> streamList = listStream.collect(Collectors.toList()); System.out.println("Stream to List"); streamList.forEach(System.out::println); // create set from stream - remove duplicates final Stream<Integer> setStream = testList.stream().sorted(); final Set<Integer> streamSet = setStream.collect(Collectors.toSet()); System.out.println("Stream to Set"); streamSet.forEach(System.out::println); // filter stream final Stream<Integer> lessThanTenStream = testList.stream().filter(n -> n < 10); System.out.println("Less Than Ten Stream"); lessThanTenStream.forEach(System.out::println); } }