How to do union, intersect, difference and reverse data in java

If you are using Sets (as you should, for all of those except reverse are Set operations), Guava provides these operations in it's Sets class.

Set<Integer> union = Sets.union(set1, set2);
Set<Integer> intersection = Sets.intersection(set1, set2);
Set<Integer> difference = Sets.difference(set1, set2);

All of these return unmodifiable views, backed by the original Sets.

See Guava Explained -> Collection Utilities -> Sets

If Lists are what you have, you can convert them to a Set by using the copy constructor present in all standard collections:

List<X> list = new ArrayList<>();
// fill up list here
Set<X> set = new HashSet<>(list);

First, the operations you describe (except reverse) are set operations, not list operations, so use HashSet or (if you need an ordering) TreeSet.

    Set<Integer> a = new TreeSet<Integer>(Arrays.asList(new Integer[]{0,2,4,5,6,8,10}));
    Set<Integer> b = new TreeSet<Integer>(Arrays.asList(new Integer[]{5,6,7,8,9,10}));

    //union
    Set<Integer> c = new TreeSet<Integer>(a);
    c.addAll(b);
    System.out.println(c);

    //intersection
    Set<Integer> d = new TreeSet<Integer>(a);
    d.retainAll(b);
    System.out.println(d);

    //difference
    Set<Integer> e = new TreeSet<Integer>(a);
    e.removeAll(b);
    System.out.println(e);

    //reverse
    List<Integer> list = new ArrayList<Integer>(a);
    java.util.Collections.reverse(list);
    System.out.println(list);

//Union 
List<Integer> c = new ArrayList<Integer>(a.size() + b.size());
addNoDups(c,a);
addNoDups(c,b);

private void addNoDups(List<Integer> toAddTo,List<Integer> iterateOver) {
    for(Integer num:iterateOver){
        if(toAddTo.indexOf(num) == -1) {
            toAddTo.add(num);
        }
    }
}

//intersection
List<Integer> c = new ArrayList<Integer> (a.size() > b.size() ?a.size():b.size());
c.addAll(a);
c.retainAll(b);

//difference a-b
List<Integer> c = new ArrayList<Integer> (a.size());
c.addAll(a);
c.removeAll(b);

Tags:

Java