I have a arrayList as follows:
[{hours: 48, cancellationCharges: 0},
{hours: 12, cancellationCharges: 10},
{hours: 0, cancellationCharges: 20}]
The above array means that from 0 to 12 hours before departure, a cancellation charge of 20% is applicable. From 12 hours to 48 hours before departure, a cancellation charge of 10% is applicable and beyond 48 hours, there is not cancellation charge at all.
I want to filter the above to find out the cancellation charges which are applicable beyond a day. i.e., in the above case, the result should be
[{hours: 48, cancellationCharges: 0},
{hours: 12, cancellationCharges: 10}]
I tried to filter by condition hours >= 24 and if the last element does not have hours as 24, I iterated again to find the first element with hours < 24. Is there a better way to solve this. I am using java12.
You just need to keep track of the last "hours" value you've seen. Remember that the Predicate
that you pass to to takeWhile
is an object, so you can keep state inside of it. It would look something like this:
cancellationRules.takeWhile(new Predicate<CancellationRule> {
private int previousHours = Integer.MAX_VALUE;
public boolean test(CancellationRule rule) {
boolean result = rule.hours >= 24 || previousHours >= 24;
previousHours = rule.hours;
return result;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With