mehnet ali
mehnet ali

Reputation: 133

How to compare Object list with Long list in java 8

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

Upvotes: 2

Views: 925

Answers (4)

mehnet ali
mehnet ali

Reputation: 133

i could write These codes

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

Upvotes: 0

Hadi
Hadi

Reputation: 17289

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

Upvotes: 4

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

Because the first list has more elements than employees list, I think your logic is inverse, instead you have to check if each elements in ids exist in employees, to solve your issue, I think you need :

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

Upvotes: 2

azro
azro

Reputation: 54148

With ids.contains(anything.getId()) the problem is that you check that the employee's id is in the allId list, this will always be true for the employee ids you have, you may check in the other way


The best is collecting the employees id, then check if each id is in it or not

Set<Long> empIds = employees.stream().map(Employee::getId).collect(Collectors.toSet());
resultMap = ids.stream().collect(Collectors.toMap(Function.identity(), empIds::contains));

You could it in one line but it won't be efficient because you would stream on employees each time

resultMap = ids.stream().collect(Collectors.toMap(id -> id, 
                         id -> employees.stream().anyMatch(e -> e.getId().equals(id))));

Upvotes: 0

Related Questions