如何在Java8中比较对象列表和长列表

如何在Java8中比较对象列表和长列表,java,java-8,java-stream,Java,Java 8,Java Stream,我正在尝试比较两个列表,第一个列表类型是Long,第二个列表类型是Employee对象,我希望在Map(Map)中设置结果 注意:第一个列表中有第二个列表中的更多项 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); 我的代码是: resultMap

我正在尝试比较两个列表,第一个列表类型是Long,第二个列表类型是Employee对象,我希望在
Map
Map
)中设置结果

注意:第一个列表中有第二个列表中的更多项

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);
我的代码是:

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());
}

因为第一个列表中的元素比employees列表中的元素多,所以我认为您的逻辑是相反的,相反,您必须检查ID中的每个元素是否存在于employees中,为了解决您的问题,我认为您需要:

// 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)));
//将员工ID存储在列表中
设置empIds=employees.stream()
.map(Employee::getId)
.collect(收集器.toSet());
//对于ids中的每个元素,检查它是否存在于empIds中
Map resultMap=ids.stream()
.collect(Collectors.toMap(Function.identity(),e->empIds.contains(e)));
试试这个:

Set<Long> employeesId =repository.getByIds(ids).stream()
          .map(Employee::getId)
          .collect(Collectors.toSet());
Set employeesId=repository.getByIds(ids.stream())
.map(Employee::getId)
.collect(收集器.toSet());
然后

Map Map=ids.stream()
.收藏(收藏家)
.toMap(Function.identity(),id->employeesId.contains(id));
使用
id.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));

我可以写这些代码

一,

二,

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)));
Set<Long> empIds = employees.stream().map(Employee::getId).collect(Collectors.toSet());
resultMap = ids.stream().collect(Collectors.toMap(Function.identity(), empIds::contains));
resultMap = ids.stream().collect(Collectors.toMap(id -> id, 
                         id -> employees.stream().anyMatch(e -> e.getId().equals(id))));
resultMap = ids.stream().collect(Collectors.toMap(id -> id, id -> list.stream().anyMatch(item -> item.getId().equals(id))));
ids.forEach(id -> resultMap.put(id, list.stream().anyMatch(item -> item.getId().equals(id))));