Java8除了提供了Stream之外,还提供了三种基础流IntStream、 DoubleStream和LongStream,基础流的最重要的作用就是避免装箱和拆箱造成的性能损耗。
装箱拆箱使用如下:
- 映射到数值流(拆箱)
- mapToInt()
- int calories = menu.stream() .mapToInt(Dish::getCalories) .sum();
- mapToInt()
- 转回对象流(装箱)
- boxed()
- IntStream intStream = menu.stream().mapToInt(Dish::getCalories); Stream stream = intStream.boxed();
- boxed()
- 注意数值流的空,数值流的空是对应类型的默认值,这时候要使用对应Option
- OptionalInt、OptionalDouble和OptionalLong
我们来看代码:
import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
/**
* IntStream、 DoubleStream和LongStream
*
*/
public class StreamTest7 {
public static void main(String[] args) {
System.out.println("IntStream生成流");
int sum = IntStream.generate(new IntSupplier() {
@Override
public int getAsInt() {
return 1;
}
}).limit(10).sum();
System.out.println("IntStream生成10个1并求和"+sum);
System.out.println("IntStream range生成递增Int Stream");
//实际代码效果同:for (int i = startInclusive; i < endExclusive ; i++) { ... }
IntStream.range(1,11).forEach(x->System.out.print(x +" "));
IntSummaryStatistics intSummaryStatistics = IntStream.range(1, 11).summaryStatistics();
double average = intSummaryStatistics.getAverage();
long count = intSummaryStatistics.getCount();
int max = intSummaryStatistics.getMax();
int min = intSummaryStatistics.getMin();
long sum1 = intSummaryStatistics.getSum();
System.out.println("IntStream生成统计信息,求平均"+average);
System.out.println("IntStream生成统计信息,求数量"+count);
System.out.println("IntStream生成统计信息,求最大值"+max);
System.out.println("IntStream生成统计信息,求最小值"+min);
System.out.println("IntStream生成统计信息,求和"+sum1);
List<Student> list = new ArrayList<>();
String[] names = {"小明","小华","小志","小东","小李","小张","小王","小周","小吴","小郑"};
for(int i=0; i<10; i++) {
Student student = Student.builder()
.name(names[i])
.age(12+i/5)
.no(i+1)
.math(85d+i).build();
list.add(student);
}
IntStream intStreamAge = list.stream().mapToInt(Student::getAge);
System.out.println("IntStream map对象类型转基础类型,年龄列表:");
intStreamAge.forEach(x->System.out.print(x+" "));
}
}
输出结果:
IntStream生成流
IntStream生成10个1并求和10
IntStream range生成递增Int Stream
1 2 3 4 5 6 7 8 9 10 IntStream生成统计信息,求平均5.5
IntStream生成统计信息,求数量10
IntStream生成统计信息,求最大值10
IntStream生成统计信息,求最小值1
IntStream生成统计信息,求和55
IntStream map对象类型转基础类型,年龄列表:
12 12 12 12 12 13 13 13 13 13