循环删除List数组特定元素
一个数组list,每次循环删除符合条件的某些元素:
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | public class ftext { public static void main(String[] args) throws Exception { cs (); } public static void cs () throws Exception { List<Integer> all = new ArrayList<Integer>(); all.add( 1 ); all.add( 2 ); all.add( 3 ); all.add( 4 ); all.add( 5 ); all.add( 6 ); all.add( 7 ); all.add( 8 ); all.add( 9 ); all.add( 10 ); int aa = 0 ; while (aa< 60 ){ if (all.size() == 0 ){ System.out.println( "已删除全部数据" ); break ; } List<Integer> xh = new ArrayList<Integer>(all); Iterator<Integer> iterator=xh.iterator(); //实例化迭代器 while (iterator.hasNext()){ Integer str=iterator.next(); //读取当前集合数据元素 if (str == aa){ all.remove(str); System.out.println( "删除" +aa+ "之后的list当中的数据为:" +all.size()); } } Thread.sleep( 10 ); System.out.println( "当前循环次数aa:" +aa); aa++; } } } |
测试结果:
当前循环次数aa:0 删除1之后的list当中的数据为:9 当前循环次数aa:1 删除2之后的list当中的数据为:8 当前循环次数aa:2 删除3之后的list当中的数据为:7 当前循环次数aa:3 删除4之后的list当中的数据为:6 当前循环次数aa:4 删除5之后的list当中的数据为:5 当前循环次数aa:5 删除6之后的list当中的数据为:4 当前循环次数aa:6 删除7之后的list当中的数据为:3 当前循环次数aa:7 删除8之后的list当中的数据为:2 当前循环次数aa:8 删除9之后的list当中的数据为:1 当前循环次数aa:9 删除10之后的list当中的数据为:0 当前循环次数aa:10 已删除全部数据
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?