1

Database is returning CompanyEntity which contains duplicate employeeID

Map<String, CompanyEntity> pp = allEmployees.stream().collect(Collectors.toMap(CompanyEntity::getEmployeeId, Function.identity()));

Exception we are getting is:

IllegalStateException: Duplicate key

Is there tweak to prevent this in Java 8 without swapping key or shall i use old way of Java 6 where i check contains and update Map?

Naman
  • 27,789
  • 26
  • 218
  • 353
fatherazrael
  • 5,511
  • 16
  • 71
  • 155
  • Why your DB allow duplication? Maybe you have something wrong with your query or DB structure? – ByeBye Nov 07 '19 at 10:58
  • @ByeBye: Yes, But need to filter out duplicates/ – fatherazrael Nov 07 '19 at 10:59
  • I did ask why? Maybe you need to fix the real problem, not the result of the problem – ByeBye Nov 07 '19 at 11:02
  • @ByeBye: Yes but i don't have access to do that and sloths in that team will not do that. The concern was already raised. So we poor chaps have to do all filtering in integrations. (Even folks sending test data in production and we are filtering it in code :-D )...INternal Project – fatherazrael Nov 07 '19 at 11:04

3 Answers3

1

A tweak could be a merge function to override the existing value in case of duplicate keys:

allEmployees.stream()
            .collect(Collectors.toMap(CompanyEntity::getEmployeeId, 
                 Function.identity(), (a,b) -> b))

But it would be a lot better to define the existing implementation as quoted where i check contains and update Map. If you check for the existence and do not update (put), you should use (a,b) -> a instead.

Naman
  • 27,789
  • 26
  • 218
  • 353
1

something like this worked for me:

// this.fsRepo.getDosIdsWithDcs(dosIds) basically returns a List<>

 return this.fsRepo.getDosIdsWithDcs(dosIds).
        stream().collect
                (Collectors.toMap(YourModelDosClass::getDosId, v->v,
                        (v1,v2) -> v1));
Alferd Nobel
  • 3,185
  • 2
  • 30
  • 35
0

You can use a groupingby collector. This will give you unique employeeId values and a list of occurences. In the second step in the groupingby collector you can get the first element of the list See also Stream groupingBy: reducing to first element of list and https://www.baeldung.com/java-groupingby-collector

FredvN
  • 504
  • 1
  • 3
  • 14