publicclassIntStreamIterateGenerate{publicstaticvoidmain(String[] args){IntStream.iterate(1, x -> x *2).limit(5).forEach(x ->System.out.print(x +" "));System.out.println();IntStream.iterate(0, x -> x +3).limit(5).forEach(x ->System.out.print(x +" "));System.out.println();Random r =newRandom();IntStream.generate(()-> r.nextInt(50)).limit(5).forEach(x ->System.out.print(x +" "));}}
publicclassIntStreamOperations{publicstaticvoidmain(String[] args){int[] values ={3,13,6,-1,4,8,2,5,9};// Display original valuesSystem.out.print("Original values: ");IntStream.of(values).forEach(value ->System.out.printf("%d ", value));// count, min, max, sum, and average of the valueslong count =IntStream.of(values).count();System.out.printf("%nCount: %d%n", count);int min =IntStream.of(values).min().getAsInt();System.out.printf("Min: %d%n", min);int max =IntStream.of(values).max().getAsInt();System.out.printf("Max: %d%n", max);int sum =IntStream.of(values).sum();System.out.printf("Sum: %d%n", sum);double average =IntStream.of(values).average().getAsDouble();System.out.printf("Average: %f%n", average);}}
publicclassIntStreamReduce{publicstaticvoidmain(String[] args){int[] values ={1,2,3,4,5};int sum =IntStream.of(values).reduce(0,(x, y)-> x + y);System.out.println("Sum: "+ sum);int sumOfSquares =IntStream.of(values).reduce(0,(x, y)-> x + y * y);System.out.println("Sum of squares: "+ sumOfSquares);int product =IntStream.of(values).reduce(1,(x, y)-> x * y);System.out.println("Product: "+ product);}}
Sum: 15
Sum of squares: 55
Product: 120
Filtering, mapping, and sorting
publicclassIntStreamFilterSortMap{publicstaticvoidmain(String[] args){int[] values ={8,3,1,4,7,6,5,2};IntStream.of(values).filter(i -> i %2==0).map(i -> i * i).sorted().forEach(i ->System.out.printf("%d ", i));}}
4 16 36 64
Finding and matching
publicclassIntStreamMatchFind{publicstaticvoidmain(String[] args){boolean allEven =IntStream.range(0,10).allMatch(value -> value %2==0);System.out.printf("All numbers are even: %b%n", allEven);boolean anyEven =IntStream.range(0,10).anyMatch(value -> value %2==0);System.out.printf("Some number is even: %b%n", anyEven);int first =IntStream.range(0,10).findFirst().getAsInt();System.out.printf("First number: %d%n", first);int any =IntStream.range(0,10).findAny().getAsInt();System.out.printf("Any number: %d%n", any);}}
All numbers are even: false
Some number is even: true
First number: 0
Any number: 0