[英]How to compare Object list with Long list in java 8
我正在嘗試比較 2 個列表,第一個列表類型是 Long,第二個列表類型是 Employee Object,我希望結果集在Map<ID, Exists>
( Map<Long, Boolean>
)中。
注意:第一個列表有更多來自第二個列表的項目
List<Employee> employees = List.of(new Employee(2), new Employee(4), new Employee(6));
List<Long> ids = List.of(1L, 2L, 3L, 4L, 5L, 6L);
我需要 output
1 : false
2 : true
3 : false
4 : true
5 : false
6 : true
我的代碼是:
resultMap = employees.stream().collect( Collectors.toMap(Employee::getId, (
anything ->
ids.contains(anything.getId() ) )));
for (Entry<Long, Boolean> entity : resultMap.entrySet()) {
System.out.println(entity.getKey() + " : " + entity.getValue());
}
但 output 是:
2 : true
4 : true
6 : true
嘗試這個:
Set<Long> employeesId =repository.getByIds(ids).stream()
.map(Employee::getId)
.collect(Collectors.toSet());
然后
Map<Long,Boolean> map = ids.stream()
.collect(Collectors
.toMap(Function.identity(),id->employeesId.contains(id)));
因為第一個列表比員工列表有更多的元素,我認為你的邏輯是相反的,相反你必須檢查 ids 中的每個元素是否存在於員工中,為了解決你的問題,我認為你需要:
// store the employee ids in a list
Set<Long> empIds = employees.stream()
.map(Employee::getId)
.collect(Collectors.toSet());
// for each element in ids, check if it exist in empIds or not
Map<Long, Boolean> resultMap = ids.stream()
.collect(Collectors.toMap(Function.identity(), e -> empIds.contains(e)));
使用ids.contains(anything.getId())
問題是您檢查員工的 id 是否在 allId 列表中,這對於您擁有的員工 id 始終是正確的,您可以以其他方式檢查
最好是收集員工 id,然后檢查每個 id 是否在其中
Set<Long> empIds = employees.stream().map(Employee::getId).collect(Collectors.toSet());
resultMap = ids.stream().collect(Collectors.toMap(Function.identity(), empIds::contains));
您可以在一行中執行此操作,但效率不高,因為您每次都會對員工進行 stream
resultMap = ids.stream().collect(Collectors.toMap(id -> id,
id -> employees.stream().anyMatch(e -> e.getId().equals(id))));
我可以寫這些代碼
1.
resultMap = ids.stream().collect(Collectors.toMap(id -> id, id -> list.stream().anyMatch(item -> item.getId().equals(id))));
2.
ids.forEach(id -> resultMap.put(id, list.stream().anyMatch(item -> item.getId().equals(id))));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.