Java - How to find count of items in a list in another list

David Buckley picture David Buckley · Apr 22, 2010 · Viewed 10.3k times · Source

Say I have two lists:

List<String>products = new ArrayList<String>(); 
products.add("computer"); 
products.add("phone"); 
products.add("mouse"); 
products.add("keyboard"); 

List<String>cart = new ArrayList<String>(); 
cart.add("phone"); 
cart.add("monitor"); 

I need to find how many items in the cart list exist in the products list. For the lists above, the answer would be 1 (as phone is in products and cart). If the cart list was:

List<String>cart = new ArrayList<String>(); 
cart.add("desk"); 
cart.add("chair"); 

The result would be 0. If cart contained computer, mouse, desk, chair, the result would be 2 (for computer and mouse).

Is there something in the Apache Commons Collections or the Google Collections API? I've looked through them and see ways to get a bag count, but not from another list, although it's possible I'm missing something. Right now, the only way I can think of is to iterate over the cart items and see if products contains the individual item and keep a count. I can't use containsAll as I need the count (not a boolean), and that would fail if all items in cart didn't exist in the product list (which can happen).

I'm using Java 1.6 if that matters.

Answer

Chris Gow picture Chris Gow · Apr 22, 2010

If you're willing to create another collection, you could do the following:

List<String> productsInCart = new ArrayList<String>(products);
productsInCart.retainAll(cart);

That'll give you all of the entries that appear in both cart and products.