Reputation: 1
I have the below class named BrokerInvoice which contain the following member variables
public class BrokerInvoice
{
private List<BrokerInvoiceLineItem> lineItems;
//and its corresponding setters and getters
}
I have the below java class named BrokerInvoiceLineItem as shown below which has a relationship among the top class named brokerInvoice as the below class is added in the to class as a list
public class BrokerInvoiceLineItem {
private String brokerRefId;
private double notional;
private Date dealDate;
//corresponding setters and getters
}
now in some piece of code i am getting the object of parent class that is of broker invoice itself
BrokerInvoice brokerInvoice1 = abc.findrty( brokerIdLong , serType );
now the above brokerInvoice1 object contain the entries of lineItems that is of type BrokerInvoiceLineItem also , so i want to edit the list named lineitems such that the list i am getting inside the brokerInvoice1 object as the condition is that there should be a sort of pre check that if lineitems list attributes named brokerRefId,notional,dealDate,dealDate are null then that entry should not be there in the line items list itself
so please advise how can i filter out my lineitems list residing inside brokerInvoice1 object such that there should not be no null attribute entry inside the lineitemslist if these attribute are empty
I am using Java 5 please advise how to achieve this can I achieve the same by java5
Upvotes: 0
Views: 644
Reputation: 16053
Java 5 :
private List<BrokerInvoiceLineItem> newLineItems = new ArrayList<BrokerInvoiceLineItem>();
if (brokerInvoice1 != null && brokerInvoice1.lineItems != null){
for(BrokerInvoiceLineItem brokerInvoiceLineItem : brokerInvoice1.lineItems){
if(brokerInvoiceLineItem.getBrokerRefId() != null && brokerInvoiceLineItem.getDealDate() == null){
newLineItems.add(brokerInvoiceLineItem)
}
}
}
Upvotes: 0
Reputation: 27486
If you are on Java 8 you can use removeIf
from Collection
:
listItems.removeIf(i -> i.getBrokerRefId() == null || i.getDealDate() == null);
This assuming you want to mutate the list.
If you prefer to not change the listItems
, and only get a new list without the wrong items, you can use stream filtering:
List<BrokerInvoiceLineItem> newList = listItems.stream()
.filter(i -> i.getBrokerRefId() != null)
.filter(i -> i.getDealDate() != null)
.collect(Collector.toList());
Notice, that the stream version retains items that match the predicate and the removeIf
one does the opposite, so the predicates are inverted.
Upvotes: 1