Home > Blockchain >  inline if inside List removeIf
inline if inside List removeIf

Time:01-10

I have a List, which is the result of a Criteria.list(). This Criteria retrieves data from different tables, depending on the data type I select.

I have three entities, that are linked to tables through Hibernate:

File.java

// fields
// getters and setters

Refund.java

// fields
private RefundState refundState;
// getters and setters

Quotation.java

// fields
private QuotationState quotationState;
// getters and setters

Refund and Quotation classes extend File. So, Refund and Quotation have some fields in common, that in case I want to get all Files, independently by the type, I can.

But this creates a big problem. When I retrieve all Files (both Refunds and Quotations), I need to exclude Quotations and Refunds with specific States. States are different between Quotations and Refunds, so I can't apply a Where condition in the Criteria.

So, I think I have to manually remove elements from the List of results. And I can, by doing list.removeIf(Predicate).

But, as the List is mixed of types, I can't just cast, like so:

list.removeIf(elem -> (((Refund) elem).getRefundState().getCode().equals("A")));

..because, it breaks when elem is a Quotation. So, I thought of inlining an if, like so:

list.removeIf(elem -> (elem instanceof Refund ? ((Refund) elem).getRefundState().getCode().equals("A")));

But it does not even compile. It says a bracket is missing.

I should avoid using a forEach since the ResultSet can be very big.
I can't change any classes.
I should avoid making two different Criterias and merging the two lists. I apply other Where conditions that I am not able to retrieve within the class I am executing this removeIf.

CodePudding user response:

You're using a ternary expression without the false part. If you add : false to your filter it should compile. However, anytime you have code in the format A ? B : false, replace it with A && B. In this case:

elem -> elem instanceof Refund && ((Refund) elem).getRefundState().getCode().equals("A")

If your Java is recent enough, you can even move the cast into the instanceof:

elem -> elem instanceof Refund r && r.getRefundState().getCode().equals("A")
  • Related