List集合概述
List集合是一個(gè)元素有序(每個(gè)元素都有對應(yīng)的順序索引,第一個(gè)元素索引為0)、且可重復(fù)的集合。
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集合中第一次出現(xiàn)的位置索引;
- int lastIndexOf(Object o);:返回對象o在List集合中最后一次出現(xiàn)的位置索引;
- 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):根據(jù)Comparator參數(shù)對List集合元素進(jìn)行排序;
- void replaceAll(UnaryOperator<E> operator):根據(jù)operator指定的計(jì)算規(guī)則重新設(shè)置集合的所有元素。
- ListIterator<E> listIterator();:返回一個(gè)ListIterator對象,該接口繼承了Iterator接口,在Iterator接口基礎(chǔ)上增加了以下方法,具有向前迭代功能且可以增加元素:
- bookean hasPrevious():返回迭代器關(guān)聯(lián)的集合是否還有上一個(gè)元素;
- E previous();:返回迭代器上一個(gè)元素;
- void add(E e);:在指定位置插入元素;
Java List去重
1. 循環(huán)list中的所有元素然后刪除重復(fù)
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踢除重復(fù)元素
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中重復(fù)元素,保持順序
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// 刪除ArrayList中重復(fù)元素,保持順序 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(),如果不存在就放入到另外一個(gè)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; } |
總結(jié)
到此這篇關(guān)于Java中List集合去除重復(fù)數(shù)據(jù)方法匯總的文章就介紹到這了,更多相關(guān)Java List去除重復(fù)內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/u011728105/article/details/46594963