Java中N个集合的交集

Java中N个集合的交集,java,collections,set-intersection,Java,Collections,Set Intersection,我有树集的列表。我需要列表中所有树集的交点。我检查了reatainAll它正在两套设备上工作,如果我错了,请纠正我。列表的最大大小为8 如何得到所有这些集合的交集 public class Rate implements Comparable<Rate> { private double value = 0.00; private int restuarentID = 0; //setters and getters @Override public int hashCode

我有
树集的列表
。我需要列表中所有树集的交点。我检查了
reatainAll
它正在两套设备上工作,如果我错了,请纠正我。列表的最大大小为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.00;
private int resturantid=0;
//二传手和接球手
@凌驾
公共int hashCode(){
最终整数素数=31;
int结果=1;
结果=prime*result+resturantid;
长温;
温度=双精度双精度长位(值);
结果=prime*result+(int)(temp^(temp>>>32));
返回结果;
}
@凌驾
公共布尔等于(对象obj){
if(this==obj)
返回true;
if(obj==null)
返回false;
如果(getClass()!=obj.getClass())
返回false;
其他费率=(费率)obj;
if(resturantid!=其他.resturantid)
返回false;
if(Double.doubleToLongBits(值)!=Double.doubleToLongBits(其他值))
返回false;
返回true;
}
@凌驾
公共国际比较(费率o){
int-ret=0;
if(this.getValue()>o.getValue())
ret=1;
if(this.getValue()
}您可以这样做:

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;
}
公共静态树集相交(列表集列表){
if(setList.isEmpty()){
抛出新的IllegalArgumentException(“列表中至少需要一个树集”);
}
Iterator it=setList.Iterator();
TreeSet result=新树集(it.next());
while(it.hasNext()){
result.retainal(it.next());
}
返回结果;
}

在所有集合上使用
retainAll
,一次两个。尽管使用了
TreeSet
,但如果在集合中使用,您应该在
速率中实现
equals()
hashCode()
。您需要实现
compareTo(Rate)
以编译代码;正如前面的评论中所述,您可能还希望重写
equals(Object)
。我的类实现有implementations equals、hashCode和compareTo。