java list 去除 重复值
一:
Hastset根据hashcode判断是否重复,数据不会重复
Java代码
- /** List order not maintained **/
- public static void removeDuplicate(ArrayList arlList)
- {
- HashSet h = new HashSet(arlList);
- arlList.clear();
- arlList.addAll(h);
- }
二:
通过Hashset的add方法判断是否已经添加过相同的数据,如果已存在相同的数据则不添加
Java代码
- /** List order maintained **/
- public static void removeDuplicateWithOrder(ArrayList arlList)
- {
- Set set = new HashSet();
- List newList = new ArrayList();
- for (Iterator iter = arlList.iterator(); iter.hasNext(); )
- {
- Object element = iter.next();
- if (set.add(element)) newList.add(element);
- }
- arlList.clear();
- arlList.addAll(newList);
- }
以下来自网络:
方法一:循环元素删除
// 删除ArrayList中重复元素
public static void 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);
}
}
}
System.out.println(list);
}
public static void 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);
}
}
}
System.out.println(list);
}
方法二:通过HashSet剔除
// 删除ArrayList中重复元素
public static void removeDuplicate(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
System.out.println(list);
}
public static void removeDuplicate(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
System.out.println(list);
}
方法三: 删除ArrayList中重复元素,保持顺序
// 删除ArrayList中重复元素,保持顺序
public static void removeDuplicateWithOrder(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
list.addAll(newList);
System.out.println( " remove duplicate " + list);
}
public static void removeDuplicateWithOrder(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
list.addAll(newList);
System.out.println( " remove duplicate " + list);
}
自己使用: 删除 “0.0”的值
List<List<String>> list1 = (List<List<String>>) map.get("商品入库表"); //表1 入库详细表
//删除list中 数量为 0值
for (Iterator<List<String>> item = list1.iterator(); item.hasNext(); ) {
List<String> it = item.next();
System.out.print(it);
if (it.get(4).equals("0.0")) {
item.remove();
}
}
链接地址:http://iteye.blog.163.com/blog/static/186308096201302565345510/