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":"赵六"}]}
相关推荐
C++、Java和Python的菜鸟9 分钟前
第7章 Java高级技术
java·开发语言
程序员佳佳19 分钟前
模型网关灰度不是调百分比:把放量、观测和回滚做成账本
java·数据库·人工智能·redis·gpt·aigc·embedding
Listen·Rain2 小时前
Springboot整合Ollama实现调用本地多模型
java·spring boot·后端
霸道流氓气质2 小时前
Java 工程师 AI 智能体(Agent)完整学习路线
java·人工智能·学习
aaPIXa6222 小时前
C++模板元编程:编译期计算Fibonacci数列
java·开发语言·c++
SunnyDays10112 小时前
Java 编辑 PDF:从增删改查到加密保护
java·修改 pdf·编辑 pdf
球king2 小时前
CC GUI 插件:在 IDEA 中使用 CodeX
java·ide·intellij-idea
山塘小鱼儿2 小时前
Agent多轮对话调用MCP Tools
java·ai·ai编程
豆瓣鸡3 小时前
网关、服务 userId 透传
java·微服务·gateway
bksczm3 小时前
Linux之信号量(POSIX标准)
java·开发语言