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

2025-05-29 0 94

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中的所有元素然后删除重复

?

1

2

3

4

5

6

7

8

9

10
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踢除重复元素

?

1

2

3

4

5

6
public static List removeDuplicate(List list) {

HashSet h = new HashSet(list);

list.clear();

list.addAll(h);

return list;

}

3. 删除ArrayList中重复元素,保持顺序

?

1

2

3

4

5

6

7

8

9

10

11

12

13
// 删除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集合中

?

1

2

3

4

5

6

7

8

9
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去除重复内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://blog.csdn.net/u011728105/article/details/46594963

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java中List集合去除重复数据的方法汇总 https://www.kuaiidc.com/108497.html

相关文章

发表评论
暂无评论