[英]Java 8 set stream loop and compare with array elements
我有一個包含TempDTO類型的對象列表的集合。
public class TempDTO {
public String code;
//getter
//setter
}
Set<TempDTO> tempSet = service.getTempList();
tempSet has values whose code is ["01", "02", "04", "05"];
String[] lst = ["01", "02"]
我想循環tempSet比較值與lst數組中的值,並且當值不匹配時我需要一個值列表。 預期的輸出是:[“ 04”,“ 05”]我嘗試過,
for(int i=0; i < lst.length; i++){
String st = lst[i];
tempSet.stream().forEach(obj -> {
if((obj.getCode().equals(st) )){
logger.debug(" equal " + obj.getCode());
} else {
logger.debug("not equal " + obj.getCode());
}
});
}
您可以使用:
// convert array(lst) to arrayList
List<String> arrList = Arrays.asList(lst);
// now check if the values are present or not
List<String> nonDupList = tempSet.stream()
.filter(i -> !arrList.contains(i.getCode()))
.map(TempDTO::getCode)
.collect(Collectors.toList());
輸出:
[05,04]
這將輸出所有不匹配的值:
Set<TempDTO> tempSet = new HashSet<>(Arrays.asList(
new TempDTO("01"),
new TempDTO("02"),
new TempDTO("04"),
new TempDTO("05")));
String[] arr = new String[] { "01", "02" };
List<String> list = Arrays.asList(arr);
List<String> output = tempSet
.stream()
.filter(temp -> !list.contains(temp.getCode()))
.map(temp -> temp.getCode())
.collect(Collectors.toList());
System.out.println(output);
輸出:
[04, 05]
如果要檢索TempDTO對象,請忽略.map(...)
調用
您必須執行以下步驟。
獲取所有這樣的代碼列表:
List<String> allCodesList = tempSet.stream() .map(value -> value.getCode()) .collect(Collectors.toList()) ;
您已經有了第二個列表。
boolean result = Arrays.equals(allCodesList.toArray(),lst.toArray());
這將為您提供所有列表中沒有代碼的所有TempDTO對象
tempSet = tempSet.stream()
.filter( obj -> !Arrays.stream( lst ).anyMatch( str -> str.equals( obj.getCode() ) ) )
.collect( Collectors.toSet() );
我建議使用過濾器方法,首先創建一個輔助列表以使用包含方法,創建一個函數以獲取所需的值(代碼),然后使用謂詞過濾輔助列表中未包含的值,最后收集列表中的值
// create an auxiliar list
List<String> auxLst = Arrays.asList(lst);
// map to code
Function<TempDTO, String> map = t -> t.getCode();
// condition
Predicate<String> lstNotcontains = code -> !auxLst.contains(code);
List<String> missingValues = tempSet.stream().map(map).filter(lstNotcontains).collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.