I have 2 ArrayLists that have a Array of Strings as a “component”. I want to find the “components” whose first element is the same in both ArrayLists.
To be more clear:
ArrayList One
first component => {"0", "zero"}
second component => {"1", "one"}
ArrayList Two
first component => {"1", "uno"}
second component => {"2", "two"}
I would like to loop through ArrayList Two and find {“1″,”uno”}.
So far I have a nested loop that loops through the first array and then checks the current component to each component in ArrayList Two.
for(int i=0; i<One.size(); i++)
{
for(int j=0; j<Two.size(); j++)
{
if( fileOne.get(i)[0].equals( Two.get(j)[0] ) )
{
System.out.print( Two.get(j)[0]+" " );
System.out.print( Two.get(j)[1] );
System.out.println();
}
}
}
I think there should be a better solution. Any help
Use a HashSet.
Note: A List would not work in this case, because lookups in Lists are O(N). Lookups in HashSets are O(1), so building the set (first loop) is O(N). Then going through your second array is O(M) and each lookup is O(1).
Overall, this becomes O(N) + ( O(M) * O(1) ) = O(N+M)
Edit: for Ted’s comments.