import java.util.stream.Stream; import java.util.stream.IntStream; import java.util.stream.Collectors; import java.util.function.IntSupplier; import java.util.Arrays; import java.util.*; public class Streamer { public static void main(String[] args){ int[] xs = {1,2,3,4,5,6,7,8,9}; // find the primes in the array. // there's only one stream operation here. int[] keepers = Arrays.stream(xs) // build a stream . filter(n -> prime(n)) // stream op.: only keep primes . toArray(); // collector: put back in an array System.out.println("the primes: "+Arrays.toString(keepers)); // let's sum the primes we were just under: int ans = Arrays.stream(xs) // stream builder .filter(n -> prime(n)) // stream operation .sum(); // collector: add them System.out.println("\nsum of primes in the original array:\n"+ans); } public static boolean prime(int n){ // base cases still handled directly. if (n<2){ return false; } // build a thing that generates ints from 2 and up IntSupplier twoAndUp = new IntSupplier(){ int x=2; @Override public int getAsInt(){ return x++;} }; // gratuitous use of streams here. return IntStream .generate(twoAndUp) // start with ints 2,3,4,... .limit(Math.max(0,n-2)) // only keep enough through (n-1) .filter(i-> n%i==0) // only keep ones that divide n evenly .count() == 0; // are there any left? } }