0

I am porting some Python code into Java and need to find an efficient implementation of the following Python operation:

sum([x in lstLong for x in lstShort])

where lstLong and lstShort are string lists. So here I am counting how many elements from lstShort appear in lstLong. In the Java implementation, both of these are String[]. What's the fastest way of counting this sum?

A more general question is whether there are any generic guidelines for writing "fast equivalents" in Java of Python list comprehension operations like the one above. I am mostly interested in arrays/lists of Strings, in case it makes the answer easier.

I Z
  • 5,719
  • 19
  • 53
  • 100
  • 1
    Possible duplicate of [Intersection and union of ArrayLists in Java](http://stackoverflow.com/questions/5283047/intersection-and-union-of-arraylists-in-java). Just find the length of the intersection. – erip Jan 13 '16 at 19:25
  • 1
    Even in Python, this isn't a good way to do the counting. It takes quadratic time, when something like `len(set(lstShort).intersection(lstLong))` takes average-case linear time. – user2357112 Jan 13 '16 at 19:26

1 Answers1

0

If you convert both to ArrayList<String>, you can use

lstLong.retainAll(lstShort).size();

You can do the conversion with

new ArrayList<String>(Arrays.asList(var));
Alyssa Haroldsen
  • 3,652
  • 1
  • 20
  • 35