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":"赵六"}]}
相关推荐
花卷HJ5 分钟前
Android 下载管理器封装实战:支持队列下载、取消、进度回调与自动保存相册
android·java
wanghowie7 分钟前
01.01 Spring核心|IoC容器深度解析
java·后端·spring
人道领域11 分钟前
【零基础学java】(Map集合)
java·开发语言
@淡 定11 分钟前
Seata AT模式详细实例:电商下单场景
java
杀死那个蝈坦12 分钟前
JUC并发编程day1
java·开发语言
飞Link15 分钟前
【Java】Linux(CentOS7)下安装JDK8(Java)教程
java·linux·运维·服务器
秋42716 分钟前
基于tomcat的动静分离
java·tomcat
巨人张19 分钟前
C++零基础游戏----“大鱼吃小鱼”
java·c++·游戏
伯明翰java19 分钟前
Java接口
java·开发语言
云和数据.ChenGuang44 分钟前
Java装箱与拆箱(面试核心解析)
java·开发语言·面试