java - 有没有办法在流式传输列表时检查条件

标签 java spring-boot

我有一个 Persons 实体,它有一个 contactType 字段。 现在根据联系人类型,我想将 List 映射到不同的资源文件,即 WorkContactResource 或 HomeContactResource。我将使用 java 8。

workContact=personList.stream().filter(p->p.getPhoneType == PhoneType.WORK).map(WorkResource::new).collect(Collectors.toList());

homeContact=personList.stream().filter(p->p.getPhoneType == PhoneType.HOME).map(HomeResource::new).collect(Collectors.toList());

workContact.addAll(homeContact);

我制作了两个不同的列表。 但我想要的是在流 PersonList 时,我将检查 contactType 是家庭还是工作,并且仅映射到特定资源。 如何实现这一目标。

最佳答案

我认为应该是这样的

abstract class Resource {   
}

class WorkResource extends Resource {
    public WorkResource(Person person) {
        ***********
    }
}

class HomeResource extends Resource {
    public HomeResource(Person person) {
        ***********
    }
}

Map<PhoneType, List<Resource>> contacts = personList.stream().collect(Collectors.groupingBy(p->p.getPhoneType, Collectors.mapping(Resource::new)));

然后按类型迭代映射

关于java - 有没有办法在流式传输列表时检查条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55575153/

相关文章:

java - Android - 解压、编辑和重新打包 apk

java - Intellij 终极版中未启用应用程序服务器选项卡

java - 使用spring amqp模板清除rabbitmq队列?

java - 为什么 Redis 不在 __keyevent@*__ :expired topic events? 上调用我的 MessageListener

spring-boot - 从 Spring Actuator 获取 Spring Session 信息

excel - 无法使用 Spring Boot 和 Apache POI 正确生成 Excel 文件

java - 基于 EJB 的应用程序中的依赖关系反转

java - Spring 启动 : Export identifier encountered more than once

java - 将 spring boot 应用程序拆分为多个 Web 应用程序

java - 凯撒移位密码,输入异常错误