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":"赵六"}]}
相关推荐
架构师沉默43 分钟前
Java优雅使用Spring Boot+MQTT推送与订阅
java·开发语言·spring boot
tuokuac1 小时前
MyBatis 与 Spring Boot版本匹配问题
java·spring boot·mybatis
zhysunny1 小时前
05.原型模式:从影分身术到细胞分裂的编程艺术
java·原型模式
草履虫建模2 小时前
RuoYi-Vue 项目 Docker 容器化部署 + DockerHub 上传全流程
java·前端·javascript·vue.js·spring boot·docker·dockerhub
皮皮林5512 小时前
强烈建议你不要再使用Date类了!!!
java
做一位快乐的码农3 小时前
基于Spring Boot和Vue电脑维修平台整合系统的设计与实现
java·struts·spring·tomcat·电脑·maven
77qqqiqi3 小时前
mp核心功能
java·数据库·微服务·mybatisplus
junjunyi3 小时前
高效实现 LRU 缓存机制:双向链表与哈希表的结合
java·哈希表·双向链表
Dcs4 小时前
网站响应提速60%的秘密:边缘计算正重构前端架构
java
CodeCraft Studio4 小时前
国产化Excel处理组件Spire.XLS教程:使用 Java 将 CSV 转换为 Excel
java·python·excel