java中怎么删除多表连接_在Java中从多个列表中合并和删除重复的最佳方式
對于每個ArrayList< Widget>,將每個元素添加到Set< Widget> (HashSet或TreeSet,取決于它們是否可以以某種方式進行排序,或者可以是hash),使用addAll.默認情況下,集合不包含重復項.
如果需要結束,您可以將此Set轉換為(Array)列表.
注意,如果您決定使用HashSet,您將需要為您的Widget類實現hashCode,但如果您有覆蓋的equals,則應該這樣做.
編輯:這里有一個例子:
//Either the class itself needs to implement Comparable,or a similar
//Comparable instance needs to be passed into a TreeSet
public class Widget implements Comparable
{
private final String name;
private final int id;
Widget(String n,int i)
{
name = n;
id = i;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
//Something like this already exists in your class
@Override
public boolean equals(Object o)
{
if(o != null && (o instanceof Widget)) {
return ((Widget)o).getName().equals(name) &&
((Widget)o).getId() == id;
}
return false;
}
//This is required for HashSet
//Note that if you override equals,you should override this
//as well. See: https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java
@Override
public int hashCode()
{
return ((Integer)id).hashCode() + name.hashCode();
}
//This is required for TreeSet
@Override
public int compareTo(Widget w)
{
if(id < w.getId()) return -1;
else if(id > w.getId()) return 1;
return name.compareTo(w.getName());
}
@Override
public String toString()
{
return "Widget: " + name + ",id: " + id;
}
}
如果要使用TreeSet,但不想實現Comparable< T>在您的Widget類中,您可以給該集本身一個Comparator對象:
private Set treeSet;
....
treeSet = new TreeSet(new Comparator() {
public int compare(Widget w1,Widget w2)
{
if(w1.getId() < w2.getId()) return -1;
else if(w1.getId() > w2.getId()) return 1;
return w1.getName().compareTo(w2.getName());
}
});
總結
以上是生活随笔為你收集整理的java中怎么删除多表连接_在Java中从多个列表中合并和删除重复的最佳方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: noclobber属性
- 下一篇: Android多个音频源采集,andro