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":"赵六"}]}
相关推荐
AI人工智能+电脑小能手几秒前
【大白话说Java面试题 第113题】【并发篇】第13题:说一下乐观锁的优点和缺点?
java·开发语言·面试
Mahir083 分钟前
HashMap 底层原理深度解密:从数据结构到 JDK1.7/1.8 演进全解
java·后端·面试·hashmap
小马爱打代码6 分钟前
Spring Boot 自动装配流程
java·spring boot·后端
我登哥MVP12 分钟前
SpringCloud 核心组件解析:分布式配置管理
java·spring boot·分布式·spring·spring cloud·java-ee·maven
lihao lihao13 分钟前
linux线程
java·开发语言·jvm
满怀冰雪14 分钟前
第13篇-栈算法入门-括号匹配-表达式与单调栈基础
java·算法
我是一颗柠檬18 分钟前
【Java项目技术亮点】Redis Lua脚本原子化操作:高并发场景下的终极武器
java·redis·lua
swg32132119 分钟前
Redis实现主从选举
java·前端·redis
Java 码思客21 分钟前
【ElasticSearch 从入门到架构师】第6章_分词器与文本检索
java·elasticsearch
Flittly22 分钟前
【AgentScope Java新手村系列】(6)Hook与Middleware
java·spring boot·笔记·spring·ai