Java - How to find count of items in a list in another list
        Posted  
        
            by David Buckley
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by David Buckley
        
        
        
        Published on 2010-04-22T01:05:47Z
        Indexed on 
            2010/04/22
            1:13 UTC
        
        
        Read the original article
        Hit count: 486
        
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.
© Stack Overflow or respective owner