Note that there are some explanatory texts on larger screens.

plurals
  1. POJava - How to find count of items in a list in another list
    text
    copied!<p>Say I have two lists:</p> <pre><code>List&lt;String&gt;products = new ArrayList&lt;String&gt;(); products.add("computer"); products.add("phone"); products.add("mouse"); products.add("keyboard"); List&lt;String&gt;cart = new ArrayList&lt;String&gt;(); cart.add("phone"); cart.add("monitor"); </code></pre> <p>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:</p> <pre><code>List&lt;String&gt;cart = new ArrayList&lt;String&gt;(); cart.add("desk"); cart.add("chair"); </code></pre> <p>The result would be 0. If cart contained computer, mouse, desk, chair, the result would be 2 (for computer and mouse).</p> <p>Is there something in the <a href="http://commons.apache.org/collections/userguide.html" rel="nofollow noreferrer">Apache Commons Collections</a> or the <a href="http://code.google.com/p/google-collections/" rel="nofollow noreferrer">Google Collections API</a>? 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 <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#contains(java.lang.Object)" rel="nofollow noreferrer">contains</a> the individual item and keep a count. I can't use <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html#containsAll(java.util.Collection)" rel="nofollow noreferrer">containsAll</a> 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).</p> <p>I'm using Java 1.6 if that matters.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload