如何在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);

我需要输出

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

但输出是:

2 : true
4 : true
6 : true
ljm88888888 回答:如何在Java 8中将对象列表与长列表进行比较

尝试一下:

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)));
,

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

// 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));

您可以将它排成一行,但效率不高,因为您每次都会在员工身上流媒体

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))));
本文链接:https://www.f2er.com/3132861.html

大家都在问