Java 8: streams from arrays
Stream can be created from arrays using Arrays.stream
static method. For example having an array of integers we can convert into IntStream:
int[] integers = {3, 6, 9, 12, 4, 81, 56, 7};
int sum = Arrays.stream(integers).sum();
//output
178
As we computed sum of array elements, we can get max and min elements:
int max = Arrays.stream(integers).max().getAsInt();
int min = Arrays.stream(integers).min().getAsInt();
System.out.println(max);
System.out.println(min);
//output
81
3
Streams can be created using arrays or collections, but we don’t need to create collection in order to work with streams. Let’s see in the following example:
Stream.of(1, 2, 3).map(i -> i*i).forEach(System.out::println);
//output
1
4
9