I want to implement the union, intersect, difference and reverse operations in Java.
First I have 2 instances of ArrayList<Integer>
a = [0,2,4,5,6,8,10] b = [5,6,7,8,9,10]
a union b should return c = [0,2,4,5,6,7,8,9,10]
a intersect b should return c = [5,8,10]
a difference b should return c = [0,2,4]
reverse a = [10,8,6,5,4,2,0]
Something like this.
How to implement that method in Java?
Update: I have to start with this template:
package IntSet; import java.util.ArrayList; import java.util.Collection; public class IntSet { private ArrayList<Integer> intset; public IntSet(){ intset = new ArrayList<Integer>(); } public void insert(int x){ intset.add(x); } public void remove(int x){ //implement here intset.indexOf(x); } public boolean member(int x){ //implement here return true; } public IntSet intersect(IntSet a){ //implement here return a; } public IntSet union(IntSet a){ //implement here return a; } public IntSet difference(IntSet a){ //implement here IntSet b = new IntSet(); return b; }
To get the union of two sets, use the addAll() method.
Sets intersection() function | Guava | Java The returned set contains all elements that are contained by both backing sets. The iteration order of the returned set matches that of set1. Return Value: This method returns an unmodifiable view of the intersection of two sets.
A set in Java represents a mathematical set, wherein you can perform various operations such as union, intersection, and difference. You can do this with the help of addAll(), retainAll(), and removeAll() methods for the above three operations, respectively.
Union can be defined as a user-defined data type which is a collection of different variables of different data types in the same memory location. The union can also be defined as many members, but only one member can contain a value at a particular point in time.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With