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
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 89
-
2025-05-25 43
-
2025-05-29 50
-
2025-06-04 90
-
2025-05-25 36
热门评论