Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API for set operations in Java? [closed]

Tags:

java

set

api

Is there an API for Set operations like Union, intersection, difference, Cartesian product, Function from a set to another, domain restriction and range restriction of those functions, .... in Java?

Please comment on coverage (of operations) and performance.

Thanks

like image 201
Tasawer Khan Avatar asked May 03 '11 11:05

Tasawer Khan


2 Answers

Yes, the java Set class.

Via Java SE tutorial:

s1.containsAll(s2) — returns true if s2 is a subset of s1. (s2 is a subset of s1 if set s1 contains all of the elements in s2.)

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.)

s1.removeAll(s2) — transforms s1 into the (asymmetric) set difference of s1 and s2. (For example, the set difference of s1 minus s2 is the set containing all of the elements found in s1 but not in s2.)

http://download.oracle.com/javase/tutorial/collections/interfaces/set.html

like image 108
igordc Avatar answered Oct 13 '22 05:10

igordc


I don't know any API but have used following methods do such things on Set.

public static <T> Set<T> union(Set<T> setA, Set<T> setB) {
    Set<T> tmp = new TreeSet<T>(setA);
    tmp.addAll(setB);
    return tmp;
  }

  public static <T> Set<T> intersection(Set<T> setA, Set<T> setB) {
    Set<T> tmp = new TreeSet<T>();
    for (T x : setA)
      if (setB.contains(x))
        tmp.add(x);
    return tmp;
  }

  public static <T> Set<T> difference(Set<T> setA, Set<T> setB) {
    Set<T> tmp = new TreeSet<T>(setA);
    tmp.removeAll(setB);
    return tmp;
  }

  public static <T> Set<T> symDifference(Set<T> setA, Set<T> setB) {
    Set<T> tmpA;
    Set<T> tmpB;

    tmpA = union(setA, setB);
    tmpB = intersection(setA, setB);
    return difference(tmpA, tmpB);
  }

  public static <T> boolean isSubset(Set<T> setA, Set<T> setB) {
    return setB.containsAll(setA);
  }

  public static <T> boolean isSuperset(Set<T> setA, Set<T> setB) {
    return setA.containsAll(setB);
  }

Reference: Set operations: union, intersection, difference, symmetric difference, is subset, is superset

like image 35
Harry Joy Avatar answered Oct 13 '22 07:10

Harry Joy