Vijay Selvaraj
Vijay Selvaraj

Reputation: 519

Filtering collections in java

I am trying to filter the below cart based on payment method. The cart contains list of Group which in tern contains list of Items and items has list of payment methods.

Now, i want all items with payment method offered as Credit card. Is there a better way to filter it out rather than running through nested loops.

public class PaymentType {
    private String paymentType;
}

public class Items {
    private Integer itemId;
    private List<PaymentType> paymentOptions;
}

public class Group {
    private Integer sellerId;
    private List<Items> itemList;
}

public class Cart {
    private Integer cardId;
    private List<Group> group;
}

Thanks,

-Vijay

Upvotes: 1

Views: 215

Answers (3)

Woot4Moo
Woot4Moo

Reputation: 24316

One approach is to make PaymentType abstract with some common methods. Then you create subclasses such as CreditCardPayment extends PaymentType which would enable you to do something like follows:

for(CreditCardPayment payment : payments)  
{  
    ccpList.add(payment);  
}  

Upvotes: 0

nwinkler
nwinkler

Reputation: 54427

I would add methods to each class to find the objects you're interested in, e.g. a method List<Item> findItemsByPaymentType(PaymentType paymentType) to each Group and Cart. The one in Cart would then call the one on the Group class for each of its Group instances, then collecting all of the single Group results in one combined list.

This would still mean that you have to implement loops, but it would be done in a nice and clean manner in each class. Easier to test and easier to reuse.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533442

It depends on what you mean by better.

You could maintain a HashMap which stores this information. This avoids using loops but means you have to maintain a data structure which adds complexity and could be slower overall, depending on how you use it.

Without more information, I would take the simplest/shortest approach which is to use loops.

Upvotes: 1

Related Questions