有時候非要用到list的時候,但是又不要重複的數據,則下面的方法比較可行..
1. 循環list中的所有元素然後刪除重複
public static List removeDuplicate(List list) {
for ( int i = 0 ; i < list.size() - 1 ; i ++ ) {
for ( int j = list.size() - 1 ; j > i; j -- ) {
if (list.get(j).equals(list.get(i))) {
list.remove(j);
}
}
}
return list;
}
2. 通過HashSet踢除重複元素
public static List removeDuplicate(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
return list;
}
在groovy中當然也可以使用上面的兩種方法, 但groovy自己提供了unique方法來去除重複數據
def list = [1, 2, 3, 2, 4, 1, 5]
list.unique() // [1, 2, 3, 4, 5]