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

时间:2025-03-12 07:31:06

什么是stream流?

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

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

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

目录

1、Stream流 遍历(forEach)

2、Stream流 过滤(filter)

3、Stream流 排序(sortAndReversed)

4、Stream流 去重(distinct)

5、Stream流 分组()

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

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


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

首先给出我们的数据前提

User实体(用户信息) 
package .;

import ;
import ;

import ;

/**
 * @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) {
         = userId;
         = userName;
         = sex;
         = age;
         = bl;
    }

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

1、Stream流 遍历(forEach)

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

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

2、Stream流 过滤(filter)

涉及到几个关键字:

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

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

    List<User> userResultList = ();
    //过滤性别字段为"男"的用户集合
    userResultList= ().filter(
            u -> ((), "男")
    ).collect(());

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

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

    //从userList集合中查找是否存在某个值
    // anyMatch 是否有一个元素匹配
    boolean bl1 = ().anyMatch(u -> ((),"张三"));
    // noneMatch 没有元素匹配
    boolean bl2 = ().noneMatch(u -> ((),"张三"));
    // allMatch 所有元素都匹配
    boolean bl3 = ().allMatch(u -> ((),true));
    ("从userList集合中查找是否存在某个值:bl1: {},bl2:{},bl3:{}",bl1,bl2,bl3);
    //(不推荐)
    boolean bl4 = ().filter(u -> ((),"张三")).findAny().isPresent();
    ("从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 = ();
    // 排序   o1-o2:升序  o2-o1 降序
    //年龄排序(自排序)
    ((o1,o2) -> ((),()));
    //年龄排序( 升序(默认) 并且返回新对象)
    userResultList = ().sorted((User::getAge)).collect(());
    ("年龄排序( 升序(默认) 并且返回新对象):{}",userResultList);
    //年龄排序( 降序 并且返回新对象) 关键字 reversed
    userResultList = ().sorted((User::getAge).reversed()).collect(());
    ("年龄排序( 降序 并且返回新对象):{}",userResultList);
    //多条件降序排序 (先通过性别降序、再通过用户id降序 排列) 关键字 thenComparing
    userResultList = ().sorted((User::getSex).reversed().thenComparing(User::getUserId).reversed()).collect(());
    ("先通过性别降序、再通过用户id降序 排列:{}",userResultList);
}

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

4、Stream流 去重(distinct)

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

5、Stream流 分组()

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

    // 根据userId 组装list对象,对应userId的对象的某个属性成组(这里用的age 年龄)
    Map<Integer,List<Integer>> userAgeMap = ().collect((User::getUserId, (User::getAge, ())));
    ("根据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的博客-****博客

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

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