数值流
首先引入两个概念
原始类型:int、double、byte、char
引用类型:Integer、Byte、Object、List
在Java中:
①将原始类型转换为对应的引用类型的机制,这个机制叫做装箱。
②将引用类型转换为对应的原始类型,叫做拆箱。
List<Dish> menu=[{name:"糖醋排骨",calories:350},{ name:"西红柿鸡蛋",calories:181},{ name:"鸡蛋汤",calories:95}]
情况:求menu中的热量的和
int allCalories = menu.stream().map(Dish::getCalories). reduce(0,Integer::sum) ;
这段代码的问题是,它有一个暗含的拆箱成本。每个 Integer 都必须拆箱成一个原始类型.Java 8引入了三个原始类型特化流接口来解决这个问题:
IntStream 、 DoubleStream 和LongStream ,分别将流中的元素特化为 int 、 long 和 double ,从而避免了暗含的拆箱成本
优化:
转换: mapToInt()
menu.stream().mapToInt(Dish::getCalories).sum()
其中mapToInt()会把Stream转换成IntStream流。 IntStream 还支持max,min,average等方法。
转换成Stream流 在用 boxed() 方法。
IntStream intStream = menu.stream().mapToInt(Dish::getCalories);
Stream<Integer> stream = intStream.boxed();
import java.sql.SQLOutput;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Boxed {
public static void main(String[] args) {
// 生成一段[0,100)序列
List<Integer> list = IntStream.range(1, 100).boxed().collect(Collectors.toList());
System.out.println(list.stream().count());
list.stream().forEach(a->System.out.println(a));
}
}
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
最后
以上就是深情白羊最近收集整理的关于java8 数值流 装箱和拆箱讲解的全部内容,更多相关java8内容请搜索靠谱客的其他文章。
发表评论 取消回复