How to do union, intersect, difference and reverse data in java
Solution 1:
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);
Solution 2:
//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);