Stream流 最全的用法
Stream 能用来干什么?用来处理集合,通过 使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询,Stream API 提供了一种高效且易于使用的处理数据的方式
为什么用Java 8 Stream ?因为 操作简单
为什么操作简单?因为 Lambda 表达式,它极大的提高了编程效率和程序可读性
怎么操作流? 首先你的有个数据源(数组、集合),操作会产生新的流对象,原来的流对象不会改变
流用法有结束操作,这种代码不是你写了一个方法就执行一个方法,而是最后触发结束操作的时候才统一执行的,collect、foreach 方法就是一种结束方法,详情看代码及结果参考 2.映射map、flatMap用法 部分
// 集合创建流
List<String> list = new ArrayList<>();
// 获取一个顺序流
Stream<String> listStream = list.stream();
// 获取一个并行流
Stream<String> parallelListStream = list.parallelStream();
// 数组创建流
Integer[] nums = new Integer[] { 1, 2, 3, 4, 5 };
Stream<Integer> arrStream = Arrays.stream(nums);
arrStream.forEach(System.out::println);// 1 2 3 4 5
// 静态方法of创建流
Stream<Integer> ofStream = Stream.of(1, 2, 3, 4, 5);
ofStream.forEach(System.out::println);// 1 2 3 4 5
// 静态方法iterate 创建流
Stream<Integer> iterateStream = Stream.iterate(1, (x) -> x + 10).limit(4);
iterateStream.forEach(System.out::println); // 1 11 21 31
// 静态方法generate 创建流
Stream<Double> generateStream = Stream.generate(Math::random).limit(2);
generateStream.forEach(System.out::println);
//filter 判空
Stream<Integer> notNullStreamObj = Stream.of(1, 2, null, 4, 5, 6, 7, null, 2);
Stream<Integer> notNullStream = notNullStreamObj.filter(i -> (null != i));
notNullStream.forEach(System.out::println);//1 2 4 5 6 7 2
//filter 逻辑判断
Stream<Integer> logicStreamObj = Stream.of(1, 2, null, 4, 5, 6, 7, null, 2);
Stream<Integer> logicStream = logicStreamObj.filter(i -> (i != null && i > 5));
logicStream.forEach(System.out::println); // 6 7
//filter 替换
Stream<String> strStreamObj = Stream.of("aa", "ab", null, "ac", "bd", "ee");
Stream<String> strStream = strStreamObj.filter(str -> (null != str && str.contains("a")));
strStream.forEach(System.out::println); // aa ab ac
//skip 跳过
Stream<String> skipStreamObj = Stream.of("aa", "ab", null, "ac", "bd", "ee");
Stream<String> skipStream = skipStreamObj.skip(2);
skipStream.forEach(System.out::println); // null ac bd ee
//distinct 去重
Stream<String> disStreamObj = Stream.of("aa", "ab", null, "ac", "aa", "ab", null, "ee");
Stream<String> disStream = disStreamObj.distinct();
disStream.forEach(System.out::println); // aa ab null ac ee
map是将每个元素 映射成一个新元素,除非你过滤了,否则不会改变元素个数
flatMap是将原流中的每个值都变成另一个流,然后把流合并串起来,必须有返回值,拼装成新的流
//map 把包含a的元素,替换成| 注意,注意, 元素还是一个整体,对每个元素
Stream<String> mapStreamObj = Stream.of("a,b,c", "a,e,f", "g,h,i");
Stream<String> mapStream = mapStreamObj.map(str -> str.replaceAll(",", "|"));
mapStream.forEach(System.out::println); // a|b|c a|e|f h|i|j
//flatMap 可以把元素 切分后,再按照新元素组成新的字符串
Stream<String> flatMapStreamObj = Stream.of("a,b,c", "a,e,f", "g,h,i");
Stream<String> flatMapStream = flatMapStreamObj.flatMap(str -> {
String[] arr = str.split(",");
Stream<String> result = Arrays.stream(arr);
return result;
});
flatMapStream.forEach(System.out::println); //a b c d e f g h i
System.out.println("1===========");
Stream<String> peekStreamObj = Stream.of("a,b,c", "a,e,f", "g,h,i");
Stream<String> peekStream = peekStreamObj.peek(e -> System.out.println("Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> System.out.println("Mapped value: " + e));
System.out.println("2=========== peek代码结束,但是日志没打印");
Set<String> stringSet = peekStream.collect(Collectors.toSet());
System.out.println("3=========== collect结束操作,代码日志打印");
stringSet.forEach(System.out::println);
map执行结果
//看下执行结果,说明 collect才是结束操作,代码结束,但是并不是真正结束
1===========
2=========== peek代码结束,但是日志没打印
Filtered value: a,b,c
Mapped value: A,B,C
Filtered value: a,e,f
Mapped value: A,E,F
Filtered value: g,h,i
Mapped value: G,H,I
3=========== collect结束操作,代码日志打印
A,B,C
A,E,F
G,H,I
先构建一个User类
public static class User {
private String name;
private Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
然后 看下sort用法
//按字母排序
Stream<String> sortStreamObj = Stream.of("a,e,f", "a,d,c", "a,b,i");
Stream<String> sortStream = sortStreamObj.sorted();
sortStream.forEach(System.out::println); //abi adc aef
User u1 = new User("bb", 1);
User u2 = new User("aa", 2);
User u3 = new User("cc", 3);
User u4 = new User("aa", 4);
Set<User> userSet = Sets.newHashSet(u1, u2, u3, u4);
Stream<User> userStream = userSet.stream().sorted(
(obj1, obj2) -> {
if (obj1.getName().equals(obj2.getName())) {
//name相等 按age
return obj1.getAge() - obj2.getAge();
}
return obj1.getName().compareTo(obj2.getName());
}
);
userStream.forEach(System.out::println);// u2 u4 u1 u3
sort 执行结果
a,b,i
a,d,c
a,e,f
User{name='aa', age=2}
User{name='aa', age=4}
User{name='bb', age=1}
User{name='cc', age=3}
List<Integer> numLists = Arrays.asList(3, 4, 5, 6, 10);
// 全部匹配 - true
boolean allMatch1 = numLists.stream().allMatch(e -> e > 2); //true
System.out.println("allMatch1:" + allMatch1);
// 全部匹配 - true
boolean allMatch2 = numLists.stream().allMatch(e -> e > 5); //false
System.out.println("allMatch2:" + allMatch2);
// 全部都不符合 - true
boolean noneMatch = numLists.stream().noneMatch(e -> e > 20); //true
System.out.println("noneMatch:" + noneMatch);
// 任一元素符合 - true
boolean anyMatch = numLists.stream().anyMatch(e -> e > 4); //true
System.out.println("anyMatch:" + anyMatch);
//返回第一个
Integer findFirst = numLists.stream().findFirst().get(); //3
System.out.println("findFirst:" + findFirst);
//返回任一个
Integer findAny = numLists.stream().findAny().get();
System.out.println("findAny:" + findAny);
//返回 count
long count = numLists.stream().count(); //5
System.out.println("count:" + count);
//返回max
Integer max = numLists.stream().max(Integer::compareTo).get(); //10
System.out.println("max:" + max);
//返回min
Integer min = numLists.stream().min(Integer::compareTo).get();//3
System.out.println("min:" + min);
匹配执行结果
allMatch1:true
allMatch2:false
noneMatch:true
anyMatch:true
findFirst:3
findAny:3
count:5
max:10
min:3
Optional sumResult = Stream.of(1, 2, 3, 4)
.reduce((sum, item) -> {
System.out.println("sum : " + sum);
sum += item;
System.out.println("item: " + item);
System.out.println("sum+ : " + sum);
System.out.println("-----——---");
return sum;
});
System.out.println("========sumResult: " + sumResult.get());
Integer sumDefineResult = Stream.of(1, 2, 3, 4)
.reduce(100, (sum, item) -> {
System.out.println("sum : " + sum);
sum += item;
System.out.println("item: " + item);
System.out.println("sum+ : " + sum);
System.out.println("---——-----");
return sum;
});
System.out.println("========sumDefineResult: " + sumDefineResult);
reduce 执行结果
//下面是执行结果
//查看执行结果
sum : 1
item: 2
sum+ : 3
-----——---
sum : 3
item: 3
sum+ : 6
-----——---
sum : 6
item: 4
sum+ : 10
-----——---
========sumResult: 10
sum : 100
item: 1
sum+ : 101
---——-----
sum : 101
item: 2
sum+ : 103
---——-----
sum : 103
item: 3
sum+ : 106
---——-----
sum : 106
item: 4
sum+ : 110
---——-----
========sumDefineResult: 110
这是个最最最最最基本的操作,10个流操作 9个都会使用到当前操作
User s1 = new User("aa", 1);
User s2 = new User("bb", 2);
User s3 = new User("cc", 3);
User s4 = new User("dd", 2);
List<User> list = Arrays.asList(s1, s2, s3, s4);
//转换list
List<Integer> ageList = list.stream().map(User::getAge).collect(Collectors.toList()); // [1, 2, 3]
System.out.println(ageList.toString());
//转成set
Set<Integer> ageSet = list.stream().map(User::getAge).collect(Collectors.toSet()); // [1, 2, 3]
System.out.println(ageSet);
//转成map,注:key不能相同,否则报错
Map<String, Integer> userMap = list.stream().collect(Collectors.toMap(User::getName, User::getAge)); // {cc=10, bb=20, aa=10}
System.out.println(userMap);
//字符串分隔符连接
String joinName = list.stream().map(User::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)
System.out.println(joinName);
//分组
Map<Integer, List<User>> ageMap = list.stream().collect(Collectors.groupingBy(User::getAge));
System.out.println(ageMap);
//多重分组,先根据类型分再根据年龄分
Map<Integer, Map<Integer, List<User>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(User::getAge, Collectors.groupingBy(User::getAge)));
System.out.println(typeAgeMap);
//分区
//分成两部分,true 一部分age大于2岁, false 一部分age小于等于2岁
Map<Boolean, List<User>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 2));
System.out.println(partMap);
collect 执行结果
[1, 2, 3, 2]
[1, 2, 3]
{dd=2, cc=3, bb=2, aa=1}
(aa,bb,cc,dd)
{1=[User{name='aa', age=1}], 2=[User{name='bb', age=2}, User{name='dd', age=2}], 3=[User{name='cc', age=3}]}
{1={1=[User{name='aa', age=1}]}, 2={2=[User{name='bb', age=2}, User{name='dd', age=2}]}, 3={3=[User{name='cc', age=3}]}}
{false=[User{name='aa', age=1}, User{name='bb', age=2}, User{name='dd', age=2}], true=[User{name='cc', age=3}]}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq_43842093/article/details/121442288
内容来源于网络,如有侵权,请联系作者删除!