0

I have two lists which both have integers added into. I want to intersect the two lists and union. I have my code, but for some reason it won't compile.

Any suggestions as to why I can't simply LinkedList.intersection(argument, argument)?

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

public class IntegerSet 
{


    public static void main(String args[]) {


        LinkedList<Double> list1 = new LinkedList<Double>();
        list1.add((double) 5);
        list1.add((double) 15);
        list1.add((double) 3);
        list1.add((double) 15);


        LinkedList<Double> list2 = new LinkedList<Double>();
        list2.add((double) 15);
        list2.add((double) 8);
        list2.add((double) 16);
        list2.add((double) 11);

        // Calculating Intersection of two Set in Java
        LinkedList<Double> intersection = LinkedList.intersection(list1, list2);
        System.out.printf("Intersection of two Set %s and %s in Java is %s %n",
                list1.toString(), list2.toString(), intersection.toString());
        System.err.println("Number of elements common in two Set : "
                           + intersection.size());

        // Calculating Union of two Set in Java
        LinkedList<Double> union = LinkedList.union(list1, list2);
        System.out.printf("Union of two Set %s and %s in Java is %s %n",
                list1.toString(), list2.toString(), union.toString());
        System.out.println("total number of element in union of two Set is : "
                            + union.size());
    }

}
informatik01
  • 16,038
  • 10
  • 74
  • 104
user2924294
  • 37
  • 1
  • 10

1 Answers1

1

Besides the fact that trying to use intersection and union methods on a linked list is one of the most awful things you can do in terms of complexity. Also,

// Calculating Union of two Set in Java
LinkedList<Double> union = LinkedList.union(list1, list2);

A Set is not the same as a List. Further this exists in the API:

col.retainAll(otherCol) // for intersection
col.addAll(otherCol) // for union

Also see this post: Intersection and union of ArrayLists in Java

Third party library: Apache Commons CollectionUtils

Community
  • 1
  • 1
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
  • Thanks but the problem with this is that it will print: For intersection: [15.0, 15.0] For union: [15.0, 8.0, 16.0, 11.0, 15.0, 15.0] It should print only one 15.0 for the union instead of each from own list... – user2924294 Nov 12 '13 at 01:23
  • Oh totally forgot about removeAll then addAll. – user2924294 Nov 12 '13 at 01:27
  • @user2924294 As an addition. Check out the "**Set Interface Bulk Operations**" section from the Oracle's official [Java Tutorials. Trail: Collections](http://docs.oracle.com/javase/tutorial/collections/interfaces/set.html) (scroll down on that page). It covers intersection, union and also difference. – informatik01 Nov 12 '13 at 01:46