-2

I have List of TreeSet<Rate>. I need intersection of all TreeSets in the List. I checked reatainAll it is working on two sets,Correct me if i am wrong. Maximum size of List is 8.

How can i get intersection of all these sets?

public class Rate implements Comparable<Rate> {
  private double value = 0.00;
  private int restuarentID = 0;

  //setters and getters

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + restuarentID;
    long temp;
    temp = Double.doubleToLongBits(value);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Rate other = (Rate) obj;
    if (restuarentID != other.restuarentID)
      return false;
    if (Double.doubleToLongBits(value) != Double.doubleToLongBits(other.value))
      return false;
    return true;
  }

  @Override
  public int compareTo(Rate o) {
    int ret = 0;
    if (this.getValue() > o.getValue())
      ret = 1;
    if (this.getValue() < o.getValue())
      ret = -1;
    if (this.getValue() == o.getValue())
      ret = 0;
    return ret;
  }
}
Community
  • 1
  • 1
Siva Kumar
  • 632
  • 3
  • 9
  • 19

1 Answers1

2

You may do like this:

public static TreeSet<Rate> intersect(List<TreeSet<Rate>> setList) {
    if (setList.isEmpty()) {
        throw new IllegalArgumentException("Need at least one TreeSet in list");
    }
    Iterator<TreeSet<Rate>> it = setList.iterator();
    TreeSet<Rate> result = new TreeSet<>(it.next());
    while (it.hasNext()) {
        result.retainAll(it.next());
    }
    return result;
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161