Priya
Priya

Reputation: 143

How to set value inside nested forEach() in java8?

I have a case in which I am iterating the List<DiscountClass> and need to compare the list value with another List<TypeCode>, based on satisfying the condition (when Discount.code equals TypeCode.code) I need to set Discount.setCodeDescr(). How to achieve this with nested forEach loop in java 8? (I am not able to set after comparing the values in java 8 forEach).

for (Discount dis : discountList) {
    for (TypeCode code : typeCodeList) {
        if (dis.getCode().equals(code.getCode())) {
            dis.setCodeDesc(code.getCodeDesc());
        }
    }
}

Upvotes: 2

Views: 4043

Answers (2)

Kartik
Kartik

Reputation: 7917

The other answer showed how to convert a nested loop to a nested functional loop.
But instead of iterating over a list of TypeCode, it's better to use a HashMap to get random access, or an enum like this:

public enum TypeCode {
    CODE_1("description of code 1"),
    CODE_2("description of code 2");

    private String desc;

    TypeCode(String desc) {
        this.desc = desc;
    }

    public String getDesc() {
        return desc;
    }
}

public class Discount {

    private String typeCode; //assuming you can't have the type as TypeCode
    private String desc;

    public Discount(String typeCode) {
        this.typeCode = typeCode;
    }

    //getters/setters
}

Then your code will change to:

Discount d1 = new Discount("CODE_1");
Discount d2 = new Discount("CODE_2");

List<Discount> discounts = List.of(d1, d2);
discounts.forEach(discount ->
        discount.setDesc(TypeCode.valueOf(discount.getTypeCode()).getDesc()));

Upvotes: 1

phlogratos
phlogratos

Reputation: 13924

A possible solution using java 8 lambdas could look like this:

    discountList.forEach(dis -> {
        typeCodeList
          .stream()
          .filter(code -> dis.getCode().equals(code.getCode()))
          .findAny()
          .ifPresent(code -> dis.setCodeDesc(code.getCodeDesc()));
    });

For each discount you filter the TypeCodes according to the code and if you find any you set the desc poperty to the one of the found TypeCode.

Upvotes: 4

Related Questions