[英]Collecting after filtering a stream with Java 8
我有一個DTO列表,這些dto包含一個標簽列表。 我正在尋找包含2個標簽的dto,每個標簽都有自己的鍵和值。 該代碼將起作用-但它只會首先在內部過濾器上找到,我想收集而不是首先找到,如果存在多個符合該條件的對象
List<myDTO> responsesList = getAllData(parameters);
List<myDTO> result = responsesList.stream()
.filter(d ->
d.getData().getTags().stream()
.filter(t -> t.getKey().equals(key1) && t.getValue().equals(value1))
.findFirst().isPresent())
.filter(d ->
d.getData().getTags().stream()
.filter(t -> t.getKey().equals(key2) && t.getValue().equals(value2))
.findFirst().isPresent())
.collect(Collectors.toList());
我缺少什么來收集集合而不是findFirst().isPresent()
? 如果我執行Collect(collectors.toList)
則會收到類似“推斷變量T具有不兼容邊界”的錯誤消息?
實際上還不清楚您想要什么。 如果您需要收集同時具有key1 / value1標簽和key2 / value2標簽的所有myDTO
對象,則您的代碼已經可以使用。 您可以將其縮短為filter(predicate).findFirst().isPresent()
可以用anyMatch(predicate)
代替:
List<myDTO> result = responsesList.stream()
.filter(d ->
d.getData().getTags().stream()
.anyMatch(t -> t.getKey().equals(key1) && t.getValue().equals(value1)))
.filter(d ->
d.getData().getTags().stream()
.anyMatch(t -> t.getKey().equals(key2) && t.getValue().equals(value2)))
.collect(Collectors.toList());
您也可以將兩個filters
合並為單個謂詞,盡管這是一個問題:
List<myDTO> result = responsesList.stream()
.filter(d ->
d.getData().getTags().stream()
.anyMatch(t -> t.getKey().equals(key1) && t.getValue().equals(value1))
&&
d.getData().getTags().stream()
.anyMatch(t -> t.getKey().equals(key2) && t.getValue().equals(value2)))
.collect(Collectors.toList());
如果您實際上想收集匹配的標簽,則可能需要flatMap
:
List<myTag> result = responsesList.stream()
.flatMap(d -> d.getData().getTags().stream())
.filter(t -> t.getKey().equals(key1) && t.getValue().equals(value1) ||
t.getKey().equals(key2) && t.getValue().equals(value2))
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.