我有TreeSet<Rate>
的列表。我需要List中所有TreeSet的交集。我检查reatainAll
它正在制作两套,如果我错了,请纠正我。 List的最大大小为8。
我怎样才能得到所有这些集合的交集?
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;
}
}
答案 0 :(得分:2)
您可以这样做:
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;
}