Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify a field in each element of list in java 8 using stream

I have the following classes:

class Employee 
{
    private String name;
    private List<Address> addresses;

    //...
    //Getters and setters for all fields
}

public class Address
{
    private String city;
    private Timestamp startDate;
    private Timestamp endDate;
    private String typeOfResidence;
    private String businessCode;
    private String businessType;


    //...
    //Getters and setters for all the fields
}

Now I have an employee object which has list of addresses. Based on businessCode, I need to populate businessType.

The businessCode is already populated.

I have a function

public String public getBusinessType(String businessCode){
...

business logic...

return businessType;
}

Now please help to update businessType field in each address element.

I am trying using

List<Address> l = employee.getAddress();

IntStream.range(0, l.size).forEach();

But not sure how to call getBusinessType for each address element and update the field in each address element.

like image 246
azaveri7 Avatar asked Dec 09 '25 18:12

azaveri7


1 Answers

You could do it in place without the need to stream:

yourList.forEach(x -> {
   x.setBusinessType(YourClass.getBusinessType(x.getBusinessCode())) 
})
like image 50
Eugene Avatar answered Dec 11 '25 14:12

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!