-2

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.

Vishnukk
  • 524
  • 2
  • 11
  • 27
  • Can there be duplicates? Ie, can there be `a, b, b, c` and `x, b, b, a` and you want both `b`s? – fge Apr 29 '14 at 06:20
  • 1
    Writing answers to questions that have duplicates on this site and show no effort only promotes people to continue putting forth no effort and still getting answers. – takendarkk Apr 29 '14 at 06:26

3 Answers3

1

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]

niiraj874u
  • 2,180
  • 1
  • 12
  • 19
1

try Collection#retainAll()

listA.retainAll(listB);
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49
1

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.

George Sovetov
  • 4,942
  • 5
  • 36
  • 57