Skip to content
Advertisement

For loop inside for loops code optimisation

I have an loop inside loop to remove the elements from the seconde loop, and what is present in the list has to perform certain actions. I wish to optimize the iteration and comparisons, can it be done?

How do I optimize my logic shown below to avoid so many lines of code

public MEntity getBuffer(String entityName, String Buffer, String... ignoreFields) {


            McgEntity entity = getElementsByEntityFromXml(entityName);
      int minLenghtOfEntities = 0;
            List<McgField> fieldsToRemove = new ArrayList<>();
            if (ignoreFields != null && ignoreFields.length > 0) {
                for (int i = 0; i < ignoreFields.length; i++) {
                    for (McgField field : entity.getFieldList()) {

                        if (field.getFieldName().contains(ignoreFields[i])) {
                            minLenghtOfEntities += field.getFieldLength();
                            fieldsToRemove.add(field);
                        }
                    }
                }

                entity.setLengthBuffer(entity.getLengthBuffer() - minLenghtOfEntities);
            entity.getFieldList().removeAll(fieldsToRemove);
            }

....
}

Advertisement

Answer

After minLenghtOfEntities += field.getFieldLength(); a break is missing.

With streams the code becomes a bit more structured, first collecting the fields to remove and then the entity lengths to correct.

public MEntity getBuffer(String entityName, String buffer, String... ignoreFields) {
    Objects.requireNonNull(ignoreFields);
    McgEntity entity = getElementsByEntityFromXml(entityName);
    List<McgField> fieldsToRemove = entity.getFieldList().stream()
            .filter(f -> Arrays.stream(ignoreFields)
                    .anyMatch(f.getFieldName()::contains))
            .collect(Collectors.toList());
    int minLenghtOfEntities = fieldsToRemove.stream()
            .mapToInt(McgField::getFieldLength).sum();

    entity.setLengthBuffer(entity.getLengthBuffer() - minLenghtOfEntities);
    entity.getFieldList().removeAll(fieldsToRemove);
    ...
}

Unfortunately because of contains a Set<String> ignoreFields is not better.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement