[英]Java 8 flatmap unwrap multiple objects from collection
希望在項目中使用某些流並替換當前實現的某些邏輯。 不知道這種情況是否適合Java流api。 假設我們有一個集合,我們要遍歷它並檢查集合中兩個對象的值,並且只有當兩個對象都為true時,我們才會返回填充的可選對象。
return Arrays.stream(someMultiDimensionalArray).flatMap(objectArray ->
.filter(MyClass.class::isInstance)
.filter(v -> v.value().equals(true))
//need to do something here to do, && (if another value in the collection is true also)
.findFirst();
/
boolean one = false;
for(int i=0; i<objectArray.length; i++){
if(!one && objectArray[i].hidden==true)
one = true;
if(objectArray[i].hidden == true && one)
return objectArray[i];
}
因此,您想要的是,如果數組中具有hidden == true
objecst多於1個,那么您想要第二個? (根據您的代碼的意思)。
所以它就像stream.filter(o -> o.hidden).skip(1).findFirst()
正如您在上面的評論中提到的:
如果集合中有兩個對象具有真實字段,則滿足條件。
您的if語句循環中的代碼段可以合並為:
boolean one = false;
for(int i=0; i<objectArray.length; i++){
if(!one && objectArray[i].hidden) {
one = true;
return objectArray[i];
}
}
實際上,它可以進一步簡化為:
for(int i=0; i<objectArray.length; i++){
if(objectArray[i].hidden) {
return objectArray[i];
}
}
然后使用如下所示的for-each循環:
for(??? it: objectArray){
if(it.hidden) {
return it;
}
}
然后使用流API是這樣的:
return Arrays.stream(objectArray).filter(it->it.hidden).findFirst();
也許您需要轉換實例並以第一種方法在flatMap
中返回流:
return Arrays.stream(someMultiDimensionalArray).flatMap(objectArray ->
Arrays.stream(objectArray).filter(it->it.hidden).findFirst()
.map(Stream::of).orElse(Stream.empty())
)
.filter(MyClass.class::isInstance)
.map(MyClass.class::cast)
.filter(MyClass::value)
.findFirst();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.