Suppose I have a list of strings
String[] stringOne = {"a","b","c", "potato"}; String[] stringTwo = {"potato", "13"};
These are arrays, not lists. Arrays.asList(stringOne) is the list wrapper for the array referenced by stringOne .
How to check how many times any given element in stringTwo occurs in stringOne?
new HashSet(Arrays.asList(stringOne)).retainAll(Arrays.asList(stringTwo))
will provide you with a set of elements in both.
A similar approach with Bag instead of typing will result in a count.
retainAll(Collection coll)
Remove all bag members that are not listed in this collection, taking into account the power. That is, if this coll collection contains n copies of this object, and the bag has m> n copies, then remove mn copies from the package. Also, if e is an object in the bag but !coll.contains(e) , delete e and any copy of it.
The concept of equivalence used in collection classes is defined by what is defined by Object.equals(object) , which java.lang.String overrides for comparison lexicographically.
If you want the result in an array, try myBag.toArray(new String[0]) , which dumps the contents into a string. The argument is explained in the documentation, but, in short, its tip type, which works around rejecting a broken Java array.