1

Possible Duplicate:
Common elements in two lists

I am trying to take 2 lists of integers, and search the lists to find elements which are the same. A new list will then be created with all common elements. I am able to get it to find common elements at the same position but not at different positions. My code can be viewed below:

class Share {


public static void main(String[] args) {
    ArrayList<Integer> oneList = new ArrayList<Integer>();
    ArrayList<Integer> twoList = new ArrayList<Integer>();

    oneList.add(8);
    oneList.add(2);
    oneList.add(5);
    oneList.add(4);
    oneList.add(3);

    twoList.add(1);
    twoList.add(2);
    twoList.add(3);
    twoList.add(4);
    twoList.add(5);

    System.out.println(sharedItems(oneList, twoList));
}

static List<Integer> sharedItems(List<Integer> list1, List<Integer> list2) {
    Iterator<Integer> it1 = list1.iterator();
    Iterator<Integer> it2 = list2.iterator();
    int i1 = 0;
    int i2 = 0;
    ArrayList<Integer> shareList = new ArrayList<Integer>();

    while (it1.hasNext()){
        i1 = it1.next();}
    System.out.println(i1);
     while (it2.hasNext()){
            i2 = it2.next();
            if (i1 == i2){
                shareList.add(i1);
        }
    }
    return shareList;
}



}
Community
  • 1
  • 1
James Warner
  • 147
  • 4
  • 4
  • 11

2 Answers2

3

You could use a Set instead:

Set<Integer> commonIntegers = new HashSet<Integer>(list1).retainAll(list2);

You can then either change the signature of your method and return the set as is:

static Collection<Integer> sharedItems(...) {
    return new HashSet<Integer>(list1).retainAll(list2);
}

or wrap it in a list:

return new ArrayList<Integer> (commonIntegers);
assylias
  • 321,522
  • 82
  • 660
  • 783
0

You want an intersection of your Lists. You can accomplish this using a Set and the retainAll method like this:

static List<Integer> sharedItems(List<Integer> list1, List<Integer> list2) {
    Set<Integer> intersection = new HashSet<Integer>(list1).retainAll(list2);
    return new ArrayList<Integer>(intersection);
}

You can read about set operations here: JCF Set details

Adam Arold
  • 29,285
  • 22
  • 112
  • 207