Taking a class in OOP Java and since I am completely new to the language and as of yet unaware of the many tools it has to offer I find myself fumbling in the dark for solutions to simple things, I can hardcode these problems but I feel there is far simpler ways to do this with java.util.
Assume I have a list of strings
String[] stringOne = {"a","b","c", "potato"};
String[] stringTwo = {"potato", "13"};
How do I check how many times any given item in stringTwo occurs in stringOne? Or vice versa. I would rather not double loop everytime I have this problem (or make a double-loop method).
Right now I get away with using Collections.frequency() and only looping once but is there a simpler way? Thanks.
These are “arrays”, not “lists”.
Arrays.asList(stringOne)is a list wrapper for the array referenced bystringOne.will give you the set of elements in both.
A similar approach with a
Baginstead of a set will get you counts.The notion of equivalence used in the collection classes is that defined by
Object.equals(object)whichjava.lang.Stringoverrides to compare lexicographically.If you need the result back in an array, try
myBag.toArray(new String[0])which dumps the contents to a string. The argument is explained in the documentation, but in short, its a type-hint that works around Java’s broken array variance.