java Stream
Stream将要处理的元素集合看作一种流,在流的过程中,借助Stream API对流中的元素进行操作,比如:筛选、排序、聚合等,给我们操作集合(Collection)提供了极大的便利。
Stream有几个特性:
-
stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果。
-
stream不会改变数据源,通常情况下会产生一个新的集合或一个值。
Stream流图#
Stream流的创建(开始)#
1、通过 java.util.Collection.stream() 方法用集合创建流
List<String> list = new ArrayList<String>;
// 创建一个串行(顺序)流
Stream<String> stream = list.stream();
// 创建一个并行流
Stream<String> parallelStream = list.parallelStream();
2、使用java.util.Arrays.stream(T[] array)方法用数组创建流
int[] array={1,2,3,4,5};
IntStream stream = Arrays.stream(array);
3、使用Stream的静态方法:of()
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
注: stream是顺序流,由主线程按顺序对流执行操作,而parallelStream是并行流,内部以多线程并行执行的方式对流进行操作,但前提是流中的数据处理没有顺序要求。 如果流中的数据量足够大,并行流可以加快处速度。除了直接创建并行流,还可以通过parallel()把顺序流转换成并行流:
Stream流的使用(中间操作)#
先创建一个Person类,并添加一些Person数据到List集合里面。
List<Person> list = new ArrayList<Person>();
personList.add(new Person("A", 8900,21, "male"));
personList.add(new Person("B", 7000,21, "male"));
personList.add(new Person("C", 7100,21, "female"));
personList.add(new Person("D", 8200, 21, "female"));
personList.add(new Person("E", 9500,20, "male"));
class Person {
private String name; // 姓名
private int salary; // 薪资
private int age; // 年龄
private String sex; //性别
public Person(String name, int salary, int age,String sex) {
this.name = name;
this.salary = salary;
this.age = age;
this.sex = sex;
}
// 省略了get和set
}
1.filter(过滤)<br /#
筛选员工中工资高于8000的人,并形成新的集合
List<String> filterList = list.stream().filter(x -> x.getSalary() > 8000).map(Person::getName)
.collect(Collectors.toList());
2.map和flatMap(映射)
#
map的使用(将员工的薪资全部增加1000)
List<Person> personListNew = list.stream().map(person -> {
person.setSalary(person.getSalary() + 1000);
return person;
}).collect(Collectors.toList());
flatMap的使用
#
将两个字符数组合并成一个新的字符数组
List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");
List<String> listNew = list.stream().flatMap(s -> {
// 将每个元素转换成一个stream
String[] split = s.split(",");
Stream<String> s2 = Arrays.stream(split);
return s2;
}).collect(Collectors.toList());
3.去重、合并、跳过、截取(concat、distinct、skip、limit)#
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" };
//创建两个流
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
// concat:合并两个流
// distinct:去重
List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
// limit:限制从流中获得前n个数据
List<String> collect = stream1.limit(2).collect(Collectors.toList());
// skip:跳过前n个数据
List<String> collect2 = stream2.skip(2).collect(Collectors.toList());
System.out.println("流合并:" + newList);
System.out.println("limit:" + collect);
System.out.println("skip:" + collect2);
4.排序(sorted)#
sorted,中间操作。有两种排序:
-
sorted():自然排序,流中元素需实现Comparable接口
-
sorted(Comparator com):Comparator排序器自定义排序
// 按工资升序排序(自然排序)
List<String> newList = list.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
.collect(Collectors.toList());
// 按工资倒序排序.reversed()
List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
.map(Person::getName).collect(Collectors.toList());
// 先按工资再按年龄升序排序.thenComparing
List<String> newList3 = personList.stream()
.sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
.collect(Collectors.toList());
// 自定义排序,先按工资再按年龄(降序)
List<String> newList4 = personList.stream().sorted((p1, p2) -> {
if (p1.getSalary() == p2.getSalary()) {
return p2.getAge() - p1.getAge();
} else {
return p2.getSalary() - p1.getSalary();
}
}).map(Person::getName).collect(Collectors.toList());
Stream流的终止(终止操作)#
1.聚合(max、min、count)#
//获取员工最高工资
Optional<Person> max = list.stream().max(Comparator.comparingInt(Person::getSalary));
//获取员工最低工资
Optional<Person> min= list.stream().min(Comparator.comparingInt(Person::getSalary));
//统计工资大于8000的人数
Long count = list.stream().filter(x -> x.getSalary() > 8000).count();
2.统计(counting、averaging)#
-
计数:counting
-
平均值:averagingInt、averagingLong、averagingDouble
-
最值:maxBy、minBy
-
求和:summingInt、summingLong、summingDouble
// 求总数
Long count = list.stream().collect(Collectors.counting());
// 求平均工资
Double average = list.stream().collect(Collectors.averagingDouble(Person::getSalary));
// 求最高工资
Optional<Integer> max = list.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
// 求工资之和
Integer sum = list.stream().collect(Collectors.summingInt(Person::getSalary));
3.遍历/匹配(foreach、find、match)#
List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
// 遍历输出符合条件的元素
list.stream().filter(x -> x > 6).forEach(System.out::println);
// 匹配第一个
Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
// 匹配任意(适用于并行流)
Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
// 是否包含符合特定条件的元素
boolean anyMatch = list.stream().anyMatch(x -> x > 6);
4.归集collect(toList、toSet、toMap)#
List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
Map<?, Person> map = list.stream().filter(p -> p.getSalary() > 8000)
.collect(Collectors.toMap(Person::getName, p -> p));
5.分区、分组(partitioningBy、groupingBy)#
- 分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
- 分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
// 将员工按薪资是否高于8000分组
Map<Boolean, List<Person>> part = list.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
// 将员工按性别分组
Map<String, List<Person>> group = list.stream().collect(Collectors.groupingBy(Person::getSex));
// 将员工先按性别分组,再按地区分组
Map<String, Map<String, List<Person>>> group2 = list.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
6.拼接(joining)#
List<String> list = Arrays.asList("1","2","3","4");
//以空字符拼接,输出 1234
String result= list.stream().collect(Collectors.joining());
//以“-”符号拼接,输出1-2-3-4
String result= list.stream().collect(Collectors.joining("-"));
System.out.println(result);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本