Home > Software design >  Ho to Filter List By Comparing between two lists and if an id exist on second list then take the val
Ho to Filter List By Comparing between two lists and if an id exist on second list then take the val

Time:07-14

I have two list appIndustries and tenantAppIndustries both having List of values :

    List<String> industries = new ArrayList<>();
    List<AppIndustryDto> appIndustries ;
    List<AppIndustryDto> tenantAppIndustries ;

    public class AppIndustryDto {
    public String appId;
    public String industryId;
   }

     Both List having data
  Inside appIndustries list I am getting ->
  a1 i1
  a1 i2
  a2 i3
  a3 i1
 Inside tenantAppIndustries list I am getting ->
 a1 i4

Final Response should be industries list should have [i1,i3,i4]

Please help me I am a beginner, thanks for you reply.

CodePudding user response:

Try this.

public static void main(String[] args) {
    List<AppIndustryDto> appIndustries = List.of(
        new AppIndustryDto("a1", "i1"),
        new AppIndustryDto("a1", "i2"),
        new AppIndustryDto("a2", "i3"),
        new AppIndustryDto("a3", "i1"));

    List<AppIndustryDto> tenantAppIndustries = List.of(
        new AppIndustryDto("a1", "i4"));

    Map<String, String> tenantMap = tenantAppIndustries.stream()
        .collect(Collectors.toMap(a -> a.appId, a -> a.industryId, (a, b) -> a));
        // If the appId is duplicated, select the first one.

    List<String> industries = appIndustries.stream()
        .map(a -> tenantMap.getOrDefault(a.appId, a.industryId))
        .distinct()
        .toList();

    System.out.println(industries);
}

output:

[i4, i3, i1]

CodePudding user response:

You can try this

List<String> list = appIndustries.stream()
.map(app -> {
  AppIndustryDto dto = tenantAppIndustries.stream()
                              .filter(t -> t.appId.equals(app.appId))
                              .findAny()
                              .orElse(null);
  return dto==null ? app.industryId : dto.industryId ;
})
.distinct()
.collect(Collectors.toList());

  • Related