-2

What is the operation used in java to represent Intersection and Union?

For example, {a,c} = 101 {c,b} = 011 and the interaction result should be 001. If I want to represent this in java 101 ∩ 011 what is the operation that should be used in correspond to ∩ and ∪ ?

wbur
  • 17
  • 8

2 Answers2

2

See the section set interface bulk operations in the official documentation. You want addAll and retainAll.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
0

Have a look to the Set Interface.

According to the above website:

s1.addAll(s2) — transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all of the elements contained in either set.)
s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.)

Here is an example:

import java.util.HashSet;
import java.util.Set;
public class Intersection
{
   public static void main(String[] args)
   {
      Set<String> s1 = new HashSet<String>();
      Set<String> s2 = new HashSet<String>();

      s1.add("a");
      s1.add("c");

      s2.add("b");
      s2.add("c");

      s1.retainAll(s2);

      System.out.println(s1);
   }
}

The output of the above is:

[c]

Rafael
  • 7,002
  • 5
  • 43
  • 52