For each loop is iterating, and everytime returning the last iteration list as result

Viewed 40

Here is my code which has for Each loop but each time it is iterating and giving the last iteration result. EX: if there are 2 iterations. Both the iteration is giving the last iteration result.

private List<someData> getsomeDetails(
            BusDetail bus)
    {
        List<someData> someDataList = new ArrayList<>();
        SSsome SSsome = new SSsome();
        
        bus.getBUDetail().get(0).getBUDetail().getBUList().forEach(bu -> {
            SSsome.setNbr(bu.getNumber());
            SSsome.setCountryCode(bu.getState());
            SSsome.setStatus("PROCESSING");
            someDataList.add(SSsome);
        });
        
        return someDataList;
    }

Can someone please help at the earliest.

Thanks in advance.

2 Answers

You are setting the values to the same object SSsome. Naturally, the last iteration will be the most recent one and hence you are seeing the values from the last iteration.

Essentially, all the objects you are adding in the list are the same having value from the most recent iteration.

You need to create objects inside the forEach and append to the list.

bus.getBUDetail().get(0).getBUDetail().getBUList().forEach(bu -> {
    SSsome SSsome = new SSsome();
    SSsome.setNbr(bu.getNumber());
    SSsome.setCountryCode(bu.getState());
    SSsome.setStatus("PROCESSING");
    someDataList.add(SSsome);
});

Note: if you create an object, update values, add to list, and then update the values again; the object inside the list will also get updated.

Your code does:

 SSsome SSsome = new SSsome();
    
 bus.getBUDetail().get(0).getBUDetail().getBUList().forEach(bu -> {
        SSsome.setNbr(bu.getNumber());
        SSsome.setCountryCode(bu.getState());
        SSsome.setStatus("PROCESSING");
        someDataList.add(SSsome);
 });

So there is only ONE SSSome, created outside the loop, so you keep modifying the same one. I think what you want to do is:

 bus.getBUDetail().get(0).getBUDetail().getBUList().forEach(bu -> {
        SSsome SSsome = new SSsome();
        SSsome.setNbr(bu.getNumber());
        SSsome.setCountryCode(bu.getState());
        SSsome.setStatus("PROCESSING");
        someDataList.add(SSsome);
 });
Related