Collectors.partitioningBy使用将List分解成两个集合

java 复制代码
package com.xxx.xx.xx;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TestDemo {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        Student student1 = new Student("张三", "踢球");
        Student student2 = new Student("李四", "滑雪");
        Student student3 = new Student("王五", "看电视");
        Student student4 = new Student("赵六", "踢球");
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        Map<Boolean, List<Student>> collect = list.stream().collect(Collectors.partitioningBy(st -> st.getHobby() == "踢球"));
        System.out.println(JSON.toJSONString(collect));
    }

    static class Student {
        private String hobby;
        private String name;

        public Student(String name, String hobby) {
            this.hobby = hobby;
            this.name = name;
        }

        public String getHobby() {
            return hobby;
        }

        public void setHobby(String hobby) {
            this.hobby = hobby;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

结果:

java 复制代码
{false:[{"hobby":"滑雪","name":"李四"},{"hobby":"看电视","name":"王五"}],true:[{"hobby":"踢球","name":"张三"},{"hobby":"踢球","name":"赵六"}]}
相关推荐
天天摸鱼的java工程师14 分钟前
CTO新项目直接上MySQL 8.0,老系统仍是5.7
java·后端·mysql
bxlj_jcj15 分钟前
解锁Java多级缓存:性能飞升的秘密武器
java·缓存·面试·架构
未来并未来17 分钟前
Redis 缓存问题及其解决方案
java·redis·缓存
快乐肚皮37 分钟前
MySQL集群模式详解:架构、优缺点与生产环境选型指南
java·mysql
季鸢1 小时前
Java设计模式之备忘录模式详解
java·设计模式·备忘录模式
异常君1 小时前
Java 逃逸分析:让你的代码性能飙升的秘密
java·面试·代码规范
迢迢星万里灬1 小时前
Java求职者面试:Spring、Spring Boot、Spring MVC与MyBatis技术深度解析
java·spring boot·spring·面试·mybatis·spring mvc
天天摸鱼的java工程师1 小时前
Nacos 2.0 + 为啥非要三个端口?一次踩坑实录
java·后端
SimonKing1 小时前
5分钟了解,Mysql事务隔离级别
java·后端·架构
代码老y1 小时前
基于springboot的图书管理系统的设计与实现
java·vue.js·spring boot·后端·毕业设计·课程设计·个人开发