Java中List集合去除重复数据的方法汇总

List集合概述

List集合是一个元素有序(每个元素都有对应的顺序索引,第一个元素索引为0)、且可重复的集合。

List集合常用方法

List是Collection接口的子接口,拥有Collection所有方法外,还有一些对索引操作的方法。

void add(int index, E element);:将元素element插入到List集合的index处; boolean addAll(int index, Collection<? extends E> c);:将集合c所有的元素都插入到List集合的index起始处; E remove(int index);:移除并返回index处的元素; int indexOf(Object o);:返回对象o在List集合中第一次出现的位置索引; int lastIndexOf(Object o);:返回对象o在List集合中最后一次出现的位置索引; E set(int index, E element);:将index索引处的元素替换为新的element对象,并返回被替换的旧元素; E get(int index);:返回集合index索引处的对象; List<E> subList(int fromIndex, int toIndex);:返回从索引fromIndex(包含)到索引toIndex(不包含)所有元素组成的子集合; void sort(Comparator<? super E> c):根据Comparator参数对List集合元素进行排序; void replaceAll(UnaryOperator<E> operator):根据operator指定的计算规则重新设置集合的所有元素。 ListIterator<E> listIterator();:返回一个ListIterator对象,该接口继承了Iterator接口,在Iterator接口基础上增加了以下方法,具有向前迭代功能且可以增加元素: bookean hasPrevious():返回迭代器关联的集合是否还有上一个元素; E previous();:返回迭代器上一个元素; void add(E e);:在指定位置插入元素;Java 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; } 

3. 删除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);  } 

4.把list里的对象遍历一遍,用list.contain(),如果不存在就放入到另外一个list集合中

public static List removeDuplicate(List list){List listTemp = new ArrayList();for(int i=0;i<list.size();i++){if(!listTemp.contains(list.get(i))){listTemp.add(list.get(i));}}return listTemp;}

总结

到此这篇关于Java中List集合去除重复数据方法汇总的文章就介绍到这了,更多相关Java List去除重复内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

才会看到属于自己的那一片晴朗的天空。

Java中List集合去除重复数据的方法汇总

相关文章:

你感兴趣的文章:

标签云: