其中去重之后的顺序能和原集合保持一致的实现方法,只有两种:LinkedHashSet 去重和 Stream 去重,而后一种去重方法无需借助新集合,是我们优先考虑的去重方法。
class TestDemo{
public static void main(String[] args) {
//初始化集合数据
List<Integer> list = new ArrayList<Integer>() {{
add(1);
add(9);
add(8);
add(2);
add(12);
add(9);
add(7);
add(2);
}};
//方法1:contains判断去重(有序)
method_1(list);
//方法2:迭代器去重(无序)
method_2(list);
//方法3:HashSet去重(无序) HashSet 天生具备“去重”的特性,那我们只需要将 List 集合转换成 HashSet 集合
HashSet<Integer> set = new HashSet<>(list);
//方法4:LinkedHashSet去重(有序) LinkedHashSet,它既能去重又能保证集合的顺序
LinkedHashSet<Integer> linkSet= new LinkedHashSet<>(list);
//方法5:TreeSet去重(无序)
TreeSet<Integer> treeSet = new TreeSet<>(list);
//方法6:JDK 8 Stream去重(有序)
method_3(list);
}
public static void method_1(List<Integer> list){
// 新集合
List<Integer> newList = new ArrayList<>(list.size());
list.forEach(i -> {
if (!newList.contains(i)) { // 如果新集合中不存在则插入
newList.add(i);
}
});
System.out.println("去重集合:" + newList);
}
public static void method_2(List<Integer> list){
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
// 获取循环的值
Integer item = iterator.next();
// 如果存在两个相同的值
if (list.indexOf(item) != list.lastIndexOf(item)) {
System.out.println(list.indexOf(item));
// 移除最后那个相同的值
iterator.remove();
}
}
System.out.println("去重集合:" + list);
}
public static void method_3(List<Integer> list){
list = list.stream().distinct().collect(Collectors.toList());
System.out.println("去重集合:" + list);
}
}
MC❤涛
今天的文章list去重_数据库去重有几种方法分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/48988.html
