How to check two line lists against eachother?

Having taken the class in OOP Java, and since I am completely new to the language and do not yet know many of the tools that it can offer, I find myself in the dark to solve simple things, I can hard-code these problems, but I believe that there are much simpler ways to do this with java.util .

Suppose I have a list of strings

 String[] stringOne = {"a","b","c", "potato"}; String[] stringTwo = {"potato", "13"}; 

How to check how many times any given element in stringTwo occurs in stringOne ? Or vice versa. I would prefer not to double the loop every time I have this problem (or the double loop method).

Right now I'm leaving with Collections.frequency() and only loop once, but is there an easier way? Thanks.

+6
source share
1 answer

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.

+3
source

All Articles