Stream流的常用方法记录

本文详细介绍了Java Stream流的各种操作,包括filter筛选、sorted排序、distinct去重、limit限制大小、skip跳过元素、map映射、flatMap转换、filter+sorted+map组合使用、统计元素个数、元素匹配、流分组操作以及获取最小最大值和求和求平均值的方法,帮助读者深入理解Java Stream的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Stream流的常用方法记录

1 filter 筛选

List<Dish> dishList = dishMapper.selectList(form);
dishList.stream()
            .filter(d -> d.getCalories() < 400) //筛选根据条件筛选
            .collect(Collectors.toList());//转为list

2 sorted 排序

List<Dish> dishList = dishMapper.selectList(form);
List<String> disNames = dishList.stream()
            .sorted(comparing(Dish::getCalories)) //根据某个字段进行排序
            .collect(Collectors.toList());//转为list

3 distinct 去重

List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
List<Integer> collect = integerList.stream().distinct().collect(Collectors.toList());

4 limit 返回指定流个数

通过 limit 方法指定返回流的个数,limit 的参数值必须 >=0,否则将会抛出异常

List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().limit(3);

5 skip 跳过流中的元素

通过 skip 方法跳过流中的元素,上述例子跳过前两个元素,所以打印结果为 2,3,4,5,skip 的参数值必须 >=0,否则将会抛出异常

List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().skip(2);

6 map 流映射

List<Dish> dishList = dishMapper.selectList(form);
List<String> disNames = dishList.stream()
            .map(Dish::getName) //提取名称
            .collect(Collectors.toList());//转为list

7 flatMap 流转换

将一个流中的每个值都转换为另一个流

List<String> wordList = Arrays.asList("Hello", "World");
List<String> strList = wordList.stream()
        .map(w -> w.split(" "))
        .flatMap(Arrays::stream)
        .distinct()
        .collect(Collectors.toList());

map(w -> w.split(" ")) 的返回值为 Stream<String[]>,我们想获取 Stream,可以通过 flatMap 方法完成 Stream ->Stream 的转换

8 filter+sorted+map组合使用

List<Dish> dishList = dishMapper.selectList(form);
List<String> disNames = dishList.stream()
            .filter(d -> d.getCalories() < 400) //筛选根据条件筛选
            .sorted(comparing(Dish::getCalories)) //根据某个字段进行排序
            .map(Dish::getName) //提取名称
            .collect(Collectors.toList());//转为list

9 统计流中元素个数

通过 count

List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().count();

通过 counting

List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().collect(counting());

10 元素匹配

提供了三种匹配方式

1.allMatch 匹配所有

2.anyMatch 匹配其中一个

3.noneMatch 全部不匹配

使用平常的方式

for (Integer i : integerList) {
    if (i > 3) {
        System.out.println("存在大于3的值");
        break;
    }
}

使用Stream流的方式

1.allMatch 匹配所有
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().allMatch(i -> i > 3)) {
    System.out.println("值都大于3");
}


2.anyMatch 匹配其中一个
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().anyMatch(i -> i > 3)) {
    System.out.println("存在大于3的值");
}

3.noneMatch 全部不匹配
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().noneMatch(i -> i > 3)) {
    System.out.println("值都小于3");
}

11 Stream流分组操作

方法1-- groupingBy(Function)

方法2-- groupingBy(Function,Collector)

方法3-- groupingBy(Function,Supplier,Collector)

参考:https://blog.csdn.net/qq_42701294/article/details/107291917

groupingBy(Function)

一个参数:一个分组器,使用提供的字段对集合元素进行分组,返回一个Map<字段,相同字段值的元素集>

List<Employee> emps = getEmps();

Map<String, List<Employee>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity));

groupingBy(Function,Collector)

2个参数:一个是分组器,按提供的字段进行分组。一个收集器,下面举例了3种用途

1、先分组再统计

/**
  *  groupBy方法2,groupingBy(Function,Collector)
  *
  *  要求:先按city分组 ,再对组里面的成员,统计总销售额
  */
@Test
public void test1(){
    List<Employee> emps = getEmps();
    for (Employee emp : emps) {
        System.out.println(emp);
    }

    Map<String, Integer> map = emps.stream().
        collect(Collectors.groupingBy(Employee::getCity, Collectors.summingInt(Employee::getSales)));

    map.forEach((key,val)->{
        System.out.println("城市:"+key+" 销售总额:"+val);
    });
}
/**
 * 城市:广州 销售总额:120
 * 城市:上海 销售总额:50
 * 城市:杭州 销售总额:180
 * 城市:北京 销售总额:50
 */

2、先分组再获取分组后对象集合的元素集合

/**
 * groupBy方法2,groupingBy(Function,Collector)
 *
 * 即:获取每个城市的姓氏集
 * 先按城市分组,再对每个组里面的员工姓名放入Set,得到每个城市的姓氏集
 */
@Test
public void test1(){
    List<Employee> emps = getEmps();
    Map<String, Set<String>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity, Collectors.mapping(Employee::getName, Collectors.toSet())));
    map.forEach((key,val)->{
        System.out.println(""+key+" ---人员姓名: "+val);
    });
}

/**
 * 上海 ---人员姓名: [葛]
 * 广州 ---人员姓名: [张, 刘, 王]
 * 杭州 ---人员姓名: [杨, 刘, 葛]
 */

3、先分组再获取分组后对象集合某个元素最大值的对象

/**
 * groupBy方法2,groupingBy(Function,Collector)
 * 要求:每个城市中销售额最大的员工
 * 先按城市分组,再求分组里面销售额最大的员工
 */
@Test
public void test1(){
    List<Employee> emps = getEmps();

    Map<String, Employee> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity,                                        Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Employee::getSales)), Optional::get)));
}

groupingBy(Function,Supplier,Collector)

参数:一个分组器,一个最终类型的生产者,一个收集器

 /**
  * 3个参数的方法:groupingBy(Function,Supplier,Collector)
  * 要求:要计算每个城市中人的姓氏集,并对城市名称进行排序
  * 先按城市分组,然后收集每个城市的姓氏集,然后放入一个TreeMap,得到最终结果。
  */
@Test
public void test7(){
    List<Employee> emps = getEmps();
    TreeMap<String, Set<String>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity, TreeMap::new, Collectors.mapping(Employee::getName, Collectors.toSet())));
    map.forEach((key,val)->{
        System.out.println("城市:"+key+" 姓氏集:"+val);
    });
}

/**
 * 城市:上海 姓氏集:[刘]
 * 城市:北京 姓氏集:[宁, 李]
 * 城市:广州 姓氏集:[张, 高, 葛]
 * 城市:杭州 姓氏集:[张, 高, 葛]
 */

12 获取流中最小最大值

通过min/max 获取最小最大值

Optional<Integer> min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional<Integer> max = menu.stream().map(Dish::getCalories).max(Integer::compareTo);

或者
OptionalInt min = menu.stream().mapToInt(Dish::getCalories).min();
OptionalInt max = menu.stream().mapToInt(Dish::getCalories).max();

对象集合的用法
List<Users> list = produceUser();
double asDouble = list.stream().mapToDouble(Users::getAge).max().getAsDouble();
int asInt = list.stream().mapToInt(Users::getAge).max().getAsInt();

通过minBy/maxBy 获取最小最大值

Optional<Integer> min = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
Optional<Integer> max = menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));

通过reduce 获取最小最大值

Optional<Integer> min = menu.stream().map(Dish::getCalories).reduce(Integer::min);
Optional<Integer> max = menu.stream().map(Dish::getCalories).reduce(Integer::max);

13 Stream流求和

根据对象中的某个字段求和

List<Users> list = produceUser();
//这里age属性是int类型可以直接求和
int sum = list.stream().mapToInt(Users::getAge).sum();

List<数值型> 求和

List<Integer> list = new ArrayList();
Integer integer = list.stream().reduce(Integer::sum).orElse(0);

List<Double> list2 = new ArrayList();
Double double = list2.stream().reduce(Double::sum).orElse(0.00);


List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();

System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());

14 Stream流求平均值

对象集合的某个字段求平均值

List<Users> list = produceUser();
double avgAge = list.stream().mapToDouble(Users::getAge).average().getAsDouble();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值