Java 8 - 如何将 Pojo 转换为其嵌入的 Pojo 属性列表

标签 java java-8

我有一个数据库调用,如果没有任何条件匹配,则可能返回 null。如果有记录匹配,则结果是一个包含嵌入对象列表的 Pojo。我想将该 Pojo 转换为其嵌入对象 id 的列表。

Foo.class 有 Bars 列表

public class Foo {
    private List<Bar> bars;
    //..setters & getters
}

Bar.class,我想将 Foo 转换为 Bar 的 Id 列表

public class Bar {
    Integer id
    //..setters & getters
}

我厌倦了使用Optional,但它总是返回到栏列表

Optional.ofNullable(fooRepo.search("some foo"))
    .map(foo -> foo.getBars()); //How can turn this into list of Bar's Id 

最佳答案

我不确定我是否理解你的问题,但我将其解释为:

A database query can return an object containing a list of references to another object, or null if no references are returned. How do I convert that object (or null) into a list of values from the referenced objects. I want an empty list if the query returned a null.

如果我的问题正确,那么我建议:

Optional<Foo> possibleFoo = Optional.ofNullable(dbQuery());
List<Integer> ids = possibleFoo
    .map(f -> f.bars.stream()
        .map(b -> b.id)
        .collect(Collectors.toList()))
    .orElse(Collections.EMPTY_LIST);

关于Java 8 - 如何将 Pojo 转换为其嵌入的 Pojo 属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35953813/

相关文章:

java - 用 java 8 API 替换两个嵌套的 for 循环

java - Google Spreadsheet getFeed 错误和理解

java - 什么都不接受也不返回什么的函数式接口(interface)

java - 在 Java 中存储不同类型对象的有序列表的最佳方法?

generics - Java 8 [无法推断类型变量]问题

Java 方法引用解析

java - 如何在 JTable 中添加行?

java - OpenEdge 10.1C 在 JDBC 中将 datetimetz 作为非标准字符串返回

java - 为什么 @AuthenticationPrincipal 返回 Authentication 而不是主体对象?

java - 用 Stream 替换 for 循环中的递归