Erga Kandly - 1 year ago 76
Java Question

# How to make Java Set

example

• A {1,2,3}

• B {1,4,5}

Code snippet:

``````a.intersect(b).print()
// Result 1 . twin between two object

a.merge(b).print()
// Result 1,2,3,4,5
``````

/**
* @param args the command line arguments
*/

``````public static void main(String[] args) {
// TODO code application logic here
Set<Integer> a = new TreeSet<Integer>();
a.remove(2);
//mengapa begituu ? karena et adalah collection yang tidak dapat memiliki elemen kembar.
System.out.println("A = " + a);

Set<Integer> b = new TreeSet<Integer>();
System.out.println("B = " + b); //hasilnya 1,2,6.
//loh?? kok bisa ? krn sy pake TreeSet, jadi udah terurut.

b.retainAll(a); //ini rumus intersect XD
for (Integer i: b)
{
System.out.print(i);
}
}
``````

}

Like this:

``````import java.util.*;
Set<Integer> a = new HashSet<Integer>();
``````

Or adding from an Array/ or multiple literals; wrap to a list, first.

``````Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals
``````

To get the intersection:

``````// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);
``````

Hope this answer helps. Vote for it!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download