Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 814
David Buckley Avatar asked Apr 22 '10 01:04

David Buckley


3 Answers

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.

like image 68
Chris Gow Avatar answered Sep 22 '22 02:09

Chris Gow


int count = 0;
for (String item : cart) {
   if (products.contains(item))
    count++;
   }
}
like image 20
anger Avatar answered Sep 20 '22 02:09

anger


For one extra line of code to sort (plus the run-time cost) and then calling a different method to do the containment check, you can get something that may very efficient for a list of products that is very long (as long as the list is efficient for random access and the list order of products isn't significant to the app):

Collections.sort(products);  // or maintain products in sort order at all times
int count = 0;
for(String i: cart) {
  if (Collections.binarySearch(products, i) >= 0) {
    count++;
  }
}
like image 44
Bert F Avatar answered Sep 21 '22 02:09

Bert F