2017-02-19 69 views
0

我有一個用例,其中包含'Location'對象的列表需要根據locationName進行處理。 我想這與Java 8流,Java Streams將列表拆分爲子列表,單獨處理這些列表並將它們合併回

private List<Payment> filterLocationsByName(List<Location> locationList) { 
    return locationList.stream().filter(l -> l.getLocationName() 
      .equalsIgnoreCase("some_location_name")) 
      .collect(Collectors.toList()); 
} 

List<Location> originalLocationList = ..... 
List<Location> someLocations = filterLocationsByName(originalLocationList); 

//logic to process someLocations list 

// do the same for another locationName 

//at the end need to return the originalList with the changes made 

我的問題是someLocations名單不是由原始列表支持。我爲someLocations元素所做的更改未填充到原始列表中。 如何將這個someLocations列表合併回原始列表,以便處理後的更改對原始列表有效?

+0

如果可以,我會有點驚訝。 –

+1

'someLocations'不支持原始列表,但它包含對原始對象的引用,這些對象仍然是從'originalLocationList'引用的。如果你想要做的只是改變現有的'Location'對象,你可以做到這一點,而不需要將任何東西合併回來。問題是什麼? –

+2

@Krishan你的問題不清楚。 'filterLocationsByName'返回'List ',你不能指定給'List '。此外,'filterLocationsByName'不會將'List '轉換爲'List '。不知道這個代碼是否會編譯。 – CKing

回答

1

流主要用於不可變的處理,因此通常不會更改原始流源(集合)。您可以嘗試forEach,但您需要自行移除。

另一種選擇是使用removeIf從Collection接口(你只需要否定條件):

locationList.removeIf(
    l -> !l.getLocationName().equalsIgnoreCase("some_location_name") 
); 

這將在地方更改列表。

相關問題