Java 中所有 N 组的交集
Intersection of all N sets in Java
我有 TreeSet<Rate>
的列表。我需要列表中所有 TreeSet 的交集。我检查了 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;
}
}
你可以这样做:
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;
}
我有 TreeSet<Rate>
的列表。我需要列表中所有 TreeSet 的交集。我检查了 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;
}
}
你可以这样做:
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;
}