Erga Kandly Erga Kandly - 4 months ago 9
Java Question

How to make Java Set

give me the answer please.
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


Correct my assignment please:
/**
* @param args the command line arguments
*/

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

Set<Integer> b = new TreeSet<Integer>();
b.add(2);
b.add(6);
b.add(1);
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);
}
}


}

Answer

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

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!

Comments