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":"赵六"}]}
相关推荐
砚底藏山河1 小时前
容错重试与指数退避:网络抖动手抖不再丢数据(魔码量化实战 #04)
java·数据库·python·金融
2501_930472442 小时前
云安全自查清单:用腾讯云助手 30 分钟完成一次权限与密钥体检
java·腾讯云
letisgo52 小时前
JAVA 高级进阶05篇《Spring容器机制:Bean生命周期与三级缓存全解》
java·spring·面试·ioc·源码分析
岁月如歌77862 小时前
分布式锁完全指南:从数据库到 Redisson 的演进
java·后端·架构
AI深栈2 小时前
第 8 章 · Tool Calling 与 Tool Search
java·人工智能
写后端的胖头鱼2 小时前
【高频面试题】spring事物失效场景(带原理 + 代码示例)
java·后端·spring·事务·事物失效
小孩玩什么2 小时前
深入理解字符串匹配算法:BF算法,KMP算法
java·c语言·开发语言·数据结构·c++·算法
长谷深风1112 小时前
Agent执行系统中的身份与版本设计
java·大数据·人工智能·ai·大模型·task·aiagent
Wang's Blog2 小时前
Java框架快速入门: Spring Security+OAuth2之UserDetails与JDBC认证实践
java·网络·spring
爱从未走散2 小时前
面试八股题
java·面试·职场和发展