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":"赵六"}]}
相关推荐
风中的小熊生气3 小时前
Spring Boot 面试知识(二):分层、IoC、异常、配置与 Redis
java·springboot
泡茶喝茶写代码3 小时前
量化数据开发实战系列(第 25 篇):基金基础接口实战:基金列表、ETF-LOF 分类、基金概况、净值数据
java·数据库·人工智能·python·mysql
shehuiyuelaiyuehao3 小时前
算法46,分治快排,排序数组
java·算法·排序算法·排序
野生技术架构师4 小时前
1200 道 JAVA 面试题(各大企业常见面试题及答案)
java·开发语言
careathers4 小时前
【数据结构】栈
java·数据结构
邪修king4 小时前
Re:Linux系统篇(二十六):文件系统(二):Ext 文件系统底层详解:从 inode、块组到软硬链接,结合 Windows 讲透文件管理本质
android·java·linux
Yyyyyy~4 小时前
【java】类和对象
java·开发语言
重生之小比特5 小时前
【Java SE】抽象类和接口
java·开发语言
Lyyaoo.5 小时前
【设计模型】策略模式
java
譕痕5 小时前
Idea 集成 智能体开发工具“千问(qwen)”
java·ide·spring·语言模型