• Java:使用Iterator迭代器删除集合中重复的选项


    结合迭代器Iterator删除集合中重复的选项,这种方法有一个缺点就是最终的结果不一定是有序的。

    public class test {
    
    	public static void main(String[] args) {
    
    //		创建一个集合
    		ArrayList list = new ArrayList<>();
    //		往集合中添加内容
    		list.add(1);
    		list.add(2);
    		list.add(3);
    		list.add(3);
    		list.add(2);
    		list.add(3);
    		list.add(4);
    		list.add(4);
    		list.add(4);
    
    //		调用删除重复项的方法
    		checkRepeat(list);
    
    //		输出删除重复项后的集合内容
    		System.out.println(list);
    
    	}
    
    	public static void checkRepeat(ArrayList list) {
    		Iterator it = list.iterator();
    
    		while (it.hasNext()) {
    //			定义一个计数器
    			int count = 0;
    
    			Integer str = (Integer) it.next();
    
    //			取出迭代器中的一个内容,循环一遍list中的内容
    			for (int i = 0; i < list.size(); i++) {
    //				如果有相同的,计数器count就加1
    				if (list.get(i) == str) {
    					count++;
    				}
    			}
    //			如果计数器的值大于等于2就说明有重复的,就删除迭代器中当前的内容
    			if (count >= 2) {
    				it.remove();
    			}
    			count = 0;
    		}
    
    	}
    
    }
    
  • 相关阅读:
    springboot @Select @Insert @Update @Delete
    列表全选与全反选
    日期控件处理
    MyCat
    eclipse中copy qualified name使用方式
    JPA
    java数组
    Java多线程
    Hadoop采样器实现全排序(报错java.io.EOFException)
    Hadoop全排序
  • 原文地址:https://www.cnblogs.com/lyd447113735/p/8993716.html
Copyright © 2020-2023  润新知