How to compare Object list with Long list in java 8

mohammad_soleimani :

I'm trying compare 2 lists , first list type is Long and second list Employee Object, and I want result set in a Map<ID, Exists> (Map<Long, Boolean>).

Note: first list has more Item from second list

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

i need output

1 : false
2 : true
3 : false
4 : true
5 : false
6 : true

my code is:

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

but output is:

2 : true
4 : true
6 : true
Hadi J :

Try this:

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

then

Map<Long,Boolean> map =  ids.stream()
                    .collect(Collectors
                        .toMap(Function.identity(),id->employeesId.contains(id)));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=323511&siteId=1