0
Rental [rentalPlanId=21.0, name=abc, onlineDate=42369.0,
 rentalPeriod=[RentalPeriod [periodName=15 data, timUnitDuration=15.0]]]
Rental [rentalPlanId=21.0, name=null, onlineDate=0.0,
 rentalPeriod=[RentalPeriod [periodName=45 data, timUnitDuration=45.0]]]

I am getting Rental objects like above one but I want final Rental like below : If rentalPlanId is same then I want to add rentalPeriod data the above rentalPeriod list to the same rental object.How to achieve this?

Rental [rentalPlanId=21.0, name=abc, onlineDate=42369.0, 
rentalPeriod=[RentalPeriod [periodName=15 data, timUnitDuration=15.0]],
[RentalPeriod [periodName=45 data, timUnitDuration=45.0]]]
public class Rental {
      private String rentalPlanId;
      private String name;
      private double onlineDate;
      
     
      
      List<RentalPeriod> rentalPeriod;
     
     
     
      public List<RentalPeriod> getRentalPeriod() {
        return rentalPeriod;
    }

    public void setRentalPeriod(List<RentalPeriod> rentalPeriod) {
        this.rentalPeriod = rentalPeriod;
    }


    public String getRentalPlanId() {
        return rentalPlanId;
    }

    public void setRentalPlanId(String rentalPlanId) {
        this.rentalPlanId = rentalPlanId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getOnlineDate() {
        return onlineDate;
    }

    public void setOnlineDate(double onlineDate) {
        this.onlineDate = onlineDate;
    }

    @Override
    public String toString() {
        return "Rental [rentalPlanId=" + rentalPlanId + ", name=" + name + ", onlineDate=" + onlineDate
                + ", rentalPeriod=" + rentalPeriod + "]";
    }
lczapski
  • 4,026
  • 3
  • 16
  • 32
user739115
  • 1,117
  • 5
  • 20
  • 41

1 Answers1

0

You can create the Map<String, Rental> and collect in it first occurrence of rentalPlanId. If next with the same rentalPlanId occur then its list rentalPeriod is added to existing one.

Something like this:

Map<String, Rental> map = new HashMap<>();
for (Rental rental: rentals) {
    if (map.containsKey(rental.getRentalPlanId())) {
        map.get(rental.getRentalPlanId()).getRentalPeriod().addAll(rental.getRentalPeriod());
    } else {
        map.put(rental.getRentalPlanId(), rental);
    }
}
List<Rental> newRentals = map.values();

Mind that in this example you modify your source objects.

lczapski
  • 4,026
  • 3
  • 16
  • 32