I have two lists of Strings which contains around 100 string items in each list in which some are common.
I want to obtain the items which are common to both the lists and store it another list.
How can this be done. Please help.
I have two lists of Strings which contains around 100 string items in each list in which some are common.
I want to obtain the items which are common to both the lists and store it another list.
How can this be done. Please help.
You can use retainAll method of List
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainClass {
public static void main(String args[]) {
String orig[] = { "a", "b", "b", "c" };
String act[] = { "x", "b", "b", "y" };
List origList = new ArrayList(Arrays.asList(orig));
List actList = Arrays.asList(act);
origList.retainAll(actList);
System.out.println(origList);
}
}
This will print [b, b]
What you want is called set intersection. (Or multiset, if you want see several duplicates.)
Simple but efficient solution is to sort both arrays and iterate over them.
for(int i = 0; i < a.length(); )
{
for(int j = 0; j < b.length(); )
{
int comparison = a[i].compareTo(b[j]);
if(comparison == 0)
{
// Add a[i] or b[j] to result here.
// If you don't want duplicate items
// in result, compare a[i] to
// last item in result and add
// only if a[i] is strictly greater.
++i;
++j;
}
else if(comparison < 0)
++i;
else
++j
}
}
If your string is long enough, you should add to HashSet
strings from first list and iterate over second array checking if element is in set.