Home > Net >  Iterating 2 or more Level of List Using Java8
Iterating 2 or more Level of List Using Java8

Time:04-29

Can anyone help me to Iterate these many Loops using java8 and at the last have to check if it contains the specified String i.e "BA" or not?

if(errorEntities!=null) {
    for(ErrorEntity errorEntity : errorEntities){
        for(ErrorItemDetail errorItem : errorEntity.getErrorItem()){
            List<EntityRef> relatedEntity = errorItem.getRelatedEntity();
            if(relatedEntity!=null || !relatedEntity.isEmpty()){
                for(EntityRef entityRef : relatedEntity){
                    return entityRef.getReferredType().equalsIgnoreCase("BA");
                }
            }
        }
    }
}

CodePudding user response:

Hope this is what you were looking for:

if(errorEntities!=null) {
    return errorEntities.stream()
        .map((ErrorEntity errorEntity) -> errorEntity.getErrorItem())
        .flatMap(Collection::stream)
        .map((ErrorItemDetail errorItemDetail) -> errorItemDetail.getRelatedEntity())
        .filter((List<EntityRef> relatedEntity) -> relatedEntity == null || relatedEntity.isEmpty())
        .flatMap(Collection::stream)
        .anyMatch((EntityRef entityRef) -> entityRef.getReferredType().equalsIgnoreCase("BA"));
}

CodePudding user response:

We have 3 levels of nested lists. At the bottom of this hierarchy we have many lists of entityRefs. We are going to collects entityRefs from all of these lists into a single stream. Then we are going to see if any one of them has reference type of "BA":

return errorEntities != null && errorEntities.stream()
        .flatMap(errorEntity -> errorEntity.getErrorItem().stream())
        .map(errorItem -> errorItem.getRelatedEntity())
        .filter(relatedEntity -> relatedEntity != null)
        .flatMap(relatedEntity -> relatedEntity.stream())
        .anyMatch(entityRef -> entityRef.getReferredType().equalsIgnoreCase("BA"))

We can also do it with method references. Here we are going to create a stream of all reference type Strings in upper case. Then we are going to see if any one of them is "BA"

return errorEntities != null && errorEntities.stream()
        .map(ErrorEntity::getErrorItem)
        .flatMap(List::stream)
        .map(ErrorItemDetail::getRelatedEntity)
        .filter(Objects::nonNull)
        .flatMap(List::stream)
        .map(EntityRef::getReferredType)
        .map(String::toUpperCase)
        .anyMatch("BA"::equals));
  • Related