NumericStream
作者:互联网
一、NumericStream
我们可以将一个Stream转化为对应的数字Stream,如mapToInt、mapToLong转化为IntStream、LongStream等(NumericStream又可以通过boxed、mapToObj方法转化回去),这样做的好处是可以节省比较多的内存开销,数据量大的话是比较明显的,因为int 4个字节的数字比Integer类型的小很多。所以能用NumericStream类型的就用。
1 package com.cy.java8; 2 3 import java.util.Arrays; 4 import java.util.stream.IntStream; 5 import java.util.stream.Stream; 6 7 public class NumericStream { 8 9 public static void main(String[] args) { 10 Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5}); 11 12 //把大于3的和打印出来 13 Integer result = stream.filter(i -> i.intValue() > 3).reduce(0, Integer::sum); 14 System.out.println(result); 15 16 //可以将Stream<Integer>转化为IntStream,再求和 17 stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5}); 18 int result2 = stream.mapToInt(Integer::intValue).filter(i -> i > 3).sum(); 19 System.out.println(result2); 20 21 //将IntStream转化为Stream<Integer> 22 stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5}); 23 IntStream intStream = stream.mapToInt(Integer::intValue); 24 Stream<Integer> boxed = intStream.boxed(); 25 26 //计算1..100数里面,有哪些数能和9,满足勾股定理,然后将这些数以[a, b, c]的形式打印出来 27 int a = 9; 28 IntStream.rangeClosed(1, 100).filter(b -> Math.sqrt(b * b + a * a) % 1 == 0) 29 .boxed() 30 .map(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)}) 31 .forEach(r -> System.out.println("a=" + r[0] + ", b=" + r[1] + ", c=" + r[2])); 32 33 //或者这么写 34 IntStream.rangeClosed(1, 100).filter(b -> Math.sqrt(b * b + a * a) % 1 == 0) 35 .mapToObj(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)}) 36 .forEach(r -> System.out.println("a=" + r[0] + ", b=" + r[1] + ", c=" + r[2])); 37 } 38 39 }
打印结果:
9 9 a=9, b=12, c=15 a=9, b=40, c=41 a=9, b=12, c=15 a=9, b=40, c=41
---
标签:stream,Stream,int,new,Integer,IntStream,NumericStream 来源: https://www.cnblogs.com/tenWood/p/11518381.html