我有一个数据库调用,如果没有任何条件匹配,则可能返回 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/