java8 List的Stream流操作 (常用篇 一)

什么是stream流?

请查看:stream | 基础知识 - 简书 (转载)

Stream 流 它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念。

Stream API 借助于Lambda表达式,极大的提高编程效率和程序可读性、可以执行非常复杂的查找、过滤和映射数据等操作。

目录

1、Stream流 遍历(forEach)

2、Stream流 过滤(filter)

3、Stream流 排序(sortAndReversed)

4、Stream流 去重(distinct)

5、Stream流 分组(Collectors.groupingBy)

        6、Stream流 toMap()  获取、转化map

        7、判断list对象是否有重复元素


会从  遍历、过滤、查询、去重、排序、分组、map 操作等方面的写案列。

首先给出我们的数据前提

User实体(用户信息) 
package com.shanghai.zrlshanghaih5service.man.vo;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Date;

/**
 * @CreateTime:  xxxx
 * @Description: User
 * @Version: 1.0
 */
@Data
public class User {

    @ApiModelProperty(value = "用户id")
    private Integer userId;

    @ApiModelProperty(value = "用户名称")
    private String userName;

    @ApiModelProperty(value = "用户性别")
    private String sex;

    @ApiModelProperty(value = "用户生日")
    private Date birthday;

    @ApiModelProperty(value = "用户年龄")
    private Integer age;

    @ApiModelProperty(value = "用户是否激活")
    private boolean bl;

    public User(Integer userId, String userName, String sex, Integer age, boolean bl) {
        this.userId = userId;
        this.userName = userName;
        this.sex = sex;
        this.age = age;
        this.bl = bl;
    }

}
        List<User> userList = Lists.newArrayList();
        userList.add(new User(1,"天一","男",16,true));
        userList.add(new User(2,"空二","女",19,true));
        userList.add(new User(3,"张三","男",18,true));
        userList.add(new User(4,"李四","女",38,true));
        userList.add(new User(5,"王五","男",18,true));
        userList.add(new User(5,"王六","男",18,true));
        userList.add(new User(5,"王七","男",18,true));

1、Stream流 遍历(forEach)

    /** 遍历 **/
    private static void forEach(List<User> userList){
        //遍历打印
        userList.forEach(System.out::println);

        //遍历每个元素赋值生日
        userList.forEach(u-> u.setBirthday(new Date()));
    }

2、Stream流 过滤(filter)

涉及到几个关键字:

count 统计总数、
anyMatch 是否有一个元素匹配、
noneMatch 没有元素匹配、
allMatch 所有元素都匹配

/** 过滤 **/
private static void filter(List<User> userList){

    List<User> userResultList = Lists.newArrayList();
    //过滤性别字段为"男"的用户集合
    userResultList= userList.stream().filter(
            u -> Objects.equals(u.getSex(), "男")
    ).collect(Collectors.toList());

    log.info("过滤性别字段为男的用户集合:{}",userResultList);

    //过滤年龄在18到30内的用户数量
    long count = userList.stream().filter(u -> u.getAge() > 18 && u.getAge() < 30).count();
    //过滤年龄在18到30内的用户集合
    userResultList = userList.stream().filter(u -> u.getAge() > 18 && u.getAge() < 30).collect(Collectors.toList());
    log.info("过滤年龄在18到30内的用户数量:{},集合:{}",count,userResultList);

    //从userList集合中查找是否存在某个值
    // anyMatch 是否有一个元素匹配
    boolean bl1 = userList.stream().anyMatch(u -> Objects.equals(u.getUserName(),"张三"));
    // noneMatch 没有元素匹配
    boolean bl2 = userList.stream().noneMatch(u -> Objects.equals(u.getUserName(),"张三"));
    // allMatch 所有元素都匹配
    boolean bl3 = userList.stream().allMatch(u -> Objects.equals(u.isBl(),true));
    log.info("从userList集合中查找是否存在某个值:bl1: {},bl2:{},bl3:{}",bl1,bl2,bl3);
    //(不推荐)
    boolean bl4 = userList.stream().filter(u -> Objects.equals(u.getUserName(),"张三")).findAny().isPresent();
    log.info("从userList集合中查找是否存在某个值:bl4:{}",bl4);
}

输出结果集:

过滤性别字段为男的用户集合:
[User(userId=1, userName=天一, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=16, bl=true),
 User(userId=3, userName=张三, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=18, bl=true), 
 User(userId=5, userName=王五, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=18, bl=true), 
 User(userId=5, userName=王六, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=18, bl=true), 
 User(userId=5, userName=王七, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=18, bl=true)]

过滤年龄在18到30内的用户数量:1,集合:[User(userId=2, userName=空二, sex=女, birthday=Mon May 15 16:18:09 CST 2023, age=19, bl=true)]

从userList集合中查找是否存在某个值:bl1: true,bl2:false,bl3:true

从userList集合中查找是否存在某个值:bl4:true

3、Stream流 排序(sortAndReversed)

关键字 thenComparing

/** 排序 **/
private static void sortAndReversed(List<User> userList){

    List<User> userResultList = Lists.newArrayList();
    // 排序   o1-o2:升序  o2-o1 降序
    //年龄排序(自排序)
    userList.sort((o1,o2) -> Integer.compare(o2.getAge(),o1.getAge()));
    //年龄排序( 升序(默认) 并且返回新对象)
    userResultList = userList.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
    log.info("年龄排序( 升序(默认) 并且返回新对象):{}",userResultList);
    //年龄排序( 降序 并且返回新对象) 关键字 reversed
    userResultList = userList.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
    log.info("年龄排序( 降序 并且返回新对象):{}",userResultList);
    //多条件降序排序 (先通过性别降序、再通过用户id降序 排列) 关键字 thenComparing
    userResultList = userList.stream().sorted(Comparator.comparing(User::getSex).reversed().thenComparing(User::getUserId).reversed()).collect(Collectors.toList());
    log.info("先通过性别降序、再通过用户id降序 排列:{}",userResultList);
}

输出结果集:(结果集太长、大家自己动手输出查看)
年龄排序( 升序(默认) 并且返回新对象
年龄排序( 降序 并且返回新对象)
多条件降序排序 (先通过性别降序、再通过用户id降序 排列) 关键字 thenComparing

4、Stream流 去重(distinct)

/** 去重 **/
private static void distinct(List<User> userList){
    List<User> userResultList=userList.stream().distinct().collect(Collectors.toList());
    log.info("去重:{}",userResultList);
}

5、Stream流 分组(Collectors.groupingBy)

/** 分组 **/
private static void group(List<User> userList){
    //对年龄分组
    Map<Integer, List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getAge));
    //循环打印
    userMap.forEach((key,value) ->{
        log.info("对年龄分组 KEY:{},value:{},",key,value);
    });

    // 根据userId 组装list对象,对应userId的对象的某个属性成组(这里用的age 年龄)
    Map<Integer,List<Integer>> userAgeMap = userList.stream().collect(Collectors.groupingBy(User::getUserId, Collectors.mapping(User::getAge, Collectors.toList())));
    log.info("根据userId 组装list对象,对应userId的对象的年龄、userAgeMap:{}",userAgeMap);

}

输出结果集:

对年龄分组 
KEY:16,
value:[User(userId=1, userName=天一, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=16, bl=true)]

KEY:18,
value:
[User(userId=3, userName=张三, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=18, bl=true), 
User(userId=5, userName=王五, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=18, bl=true), 
User(userId=5, userName=王六, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=18, bl=true),
User(userId=5, userName=王七, sex=男, birthday=Mon May 15 16:18:09 CST 2023, age=18, bl=true)]

KEY:19,
value:[User(userId=2, userName=空二, sex=女, birthday=Mon May 15 16:18:09 CST 2023, age=19, bl=true)]

KEY:38,
value:[User(userId=4, userName=李四, sex=女, birthday=Mon May 15 16:18:09 CST 2023, age=38, bl=true)]


根据userId 组装list对象,对应userId的对象的年龄、
userAgeMap:{1=[16], 2=[19], 3=[18], 4=[38], 5=[18, 18, 18]}

6、Stream流 toMap()  获取、转化map

由于太长了、所以准备单独写一篇

链接:java8 List的Stream流操作 (特别篇 二) toMap_java list tomap_DJyzh的博客-CSDN博客

7、判断list对象是否有重复元素

推荐链接:java实用小技巧:判断list是否有重复项_java判断list中的重复数据_剽悍一小兔的博客-CSDN博客

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值