
stream流式编程分为
- 首先
转化为stream中间函数的链接- 最后的
终结函数
怎么转化为stream
- 单列集合
1 | List<String> list = new ArrayList<String>(); |
- 双列集合
1 | Map<String,String> map = new HashMap<String,String>(); |
- 数组
1 | Arrays.stream(new int[0]); |
- 多个数字
1 | Stream.of(1,2,3,4).forEach(System.out::println); |
常用中间函数
注:中间函数可连接多个
filter:过滤1
2
3List<String> list = new ArrayList<String>();
Collections.addAll(list,"1","2","3","4","5","6","7","8","9");
list.stream().filter(s -> s.equals("1")).forEach(System.out::println);输出:1
map:将流中的每个元素传入给定的函数,得到一个新的流。1
Stream.of("a","b","c","d").map(String::toUpperCase).forEach(System.out::print);
输出:ABCD
limit:取前n个1
2
3List<String> list = new ArrayList<String>();
Collections.addAll(list,"1","2","3","4","5","6","7","8","9");
list.stream().limit(3).forEach(System.out::print);输出:123
skip:跳过前n个1
2
3List<String> list = new ArrayList<String>();
Collections.addAll(list,"1","2","3","4","5","6","7","8","9");
list.stream().skip(4).forEach(System.out::print);输出:56789
distinct:去重,依赖hashCode(),equals()1
2
3List<String> list = new ArrayList<String>();
Collections.addAll(list,"1","2","3","4","4","3","2","1","0");
list.stream().distinct().forEach(System.out::print);输出:12340
concat:合并两个流1
2
3
4
5List<String> l1 = new ArrayList<String>();
l1.add("1");
List<String> l2 = new ArrayList<String>();
l2.add("2");
Stream.concat(l1.stream(),l2.stream());输出:12
sorted: 排序1
2
3
4
5
6
7
8
9
10List<Integer> numbers = Arrays.asList(5, 6, 4, 3, 8, 0, 1, 9, 6, 8);
//第一种 默认
numbers.stream()
.sorted()
.forEach(System.out::println);
// 第二种 自定义排序
numbers.stream()
// 如果是b.compareTo(a)则降序 a.compareTo(b)则升序
.sorted((a, b) -> b.compareTo(a))
.forEach(System.out::println);输出:
0 1 3 4 5 6 6 8 8 9
9 8 8 6 6 5 4 3 1 0
终结函数
注:终结函数只能有一个
forEach:遍历count:求数量collect:收集
1 | lines.stream().filter(s -> s.startsWith("张")).collect(Collectors.toList()); |
toArray:转化为数组
1 | String[] strings = lines.stream().toArray(val -> new String[val]); |
reduce:收纳1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16List<Integer> asList = Arrays.asList(1, 2, 3, 4, 5);
// 示例1: 求和
Optional<Integer> sum = asList.stream()
.reduce(Integer::sum);
System.out.println("和: " + sum.orElse(0));
// 示例2: 求乘积
Optional<Integer> product = asList.stream()
.reduce((x, y) -> x * y);
System.out.println("乘积: " + product.orElse(1));
// 示例3: 求最大值
Optional<Integer> max = asList.stream()
.reduce(Integer::max);
System.out.println("最大: " + max.orElse(0));输出
和: 15
乘积: 120
最大: 5
注意事项
惰性求值:如果没有终结操作(终结函数),中间操作是不会得到执行的,即没有任何输出。流的一次性:一旦一个流对象经过一个终结操作后,这个流就不能再被使用了,只能重新创建流对象再使用。不会影响原数据:我们在流中可以对数据做很多处理,正常是不会影响原来集合中的元素的。