[英]JAVA8 Optional and Lambdas
假設我有這個class
model 層次結構:
public class A {
private Integer id;
private List<B> b;
}
和:
public class B {
private Integer id;
private List<C> c;
}
最后:
public class C {
private Integer id;
}
還有一個簡單的Service
:
@Service
public class doSome {
public void test() {
Optional<A> a = Optional.of(a) // Suppose a is an instance with full hierarchy contains values
/** *1 **/ // what I want to do
}
}
Now what I want to do at the *1
position is to use lambda to extract the Optional
value (if exixsts) and map the subrelation to obtain all id
of the C
class. 我嘗試過這樣的事情:
public void test() {
Optional<A> a = Optional.of(a);
List<Integer> temp = a.get().getB()
.stream()
.map(x -> x.getC())
.flatMap(List::stream)
.map(y -> y.getId())
.collect(Collectors.toList()); // works
}
現在我想在我的 lambda 中放入a.get().getB()
,我嘗試了幾種方法但沒有運氣。
無論如何我不明白為什么我不能使用兩個連續map
類的
.map(x -> x.getC())
.flatMap(List::stream)
.map(y -> y.getId())
without using flatMap(List::stream)
in the middle... the map
doesn't return a new Stream
of Type R (class C in this case)? 為什么我又要Stream
呢? 我哪里錯了?
- - - - - - - - - - - - 更新 - - - - - - - - -
這只是一個示例,很明顯,此處的Optional
是無用的,但在實際情況下可能來自findById()
JPA 查詢。
Holger 出於這個原因,我會將所有內容放在代碼的一部分中,執行以下操作:
public <T> T findSome(Integer id) {
Optional<T> opt = repository.findById(id);
return opt.map(opt -> opt).orElse(null);
}
我在這里閱讀了一些解決方案,如下所示:
Optional.ofNullable(MyObject.getPeople())
.map(people -> people
.stream()
.filter(person -> person.getName().equals("test1"))
.findFirst()
.map(person -> person.getId()))
.orElse(null);
我想適應我的情況,但沒有運氣。
從java-9和更高版本開始,您可以調用Optional#stream
:
List<Integer> temp = a.map(A::getB)
.stream()
.flatMap(Collection::stream)
.map(B::getC)
.flatMap(Collection::stream)
.map(C::getId)
.collect(Collectors.toList());
如果您遇到 java-8 ,您需要 map 到Stream
(或返回空的)並繼續鏈接:
List<Integer> temp = a.map(A::getB)
.map(Collection::stream)
.orElse(Stream.empty())
.map(B::getC)
.flatMap(Collection::stream)
.map(C::getId)
.collect(Collectors.toList());
注意: Optional<A> a = Optional.of(a)
無效,因為a
已經定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.