简体   繁体   English

在打印过程中跳过ArrayList的特定值

[英]Skipping a particular value of ArrayList during printing

My Code is as follows: 我的代码如下:

ArrayList<Integer> al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(3);
al.add(4);

I want the following pattern during printing: 我在打印时需要以下模式:

[1,2,4]

I tried both for loop and Iterator but I am not getting the desired output. 我同时尝试了循环和迭代器,但没有得到想要的输出。

Help me to sort out! 帮我整理一下!

I found the solution and that is 我找到了解决方案,那就是

for(int i=0;i<al.size();i++) {
if(al.get(i)!=3) 
   System.out.println(al.get(i));
  }

thanks for your help 谢谢你的帮助

Now I want to get the same output, not through printing but by deleting elements of ArrayList, I tried with the same condition but I got exception 现在我想获得相同的输出,而不是通过打印,而是通过删除ArrayList的元素,我尝试了相同的条件,但是出现了异常

and the answer is 答案是

Iterator<Integer> iter = al.iterator();
        while (iter.hasNext()) {
            if (iter.next().intValue() == 3) {
                iter.remove();
            }
        }
        System.out.println(al);

Step through all the items in the ArrayList and test if they are equal to 3 , if they are not, print them. 逐步检查ArrayList中的所有项目,并测试它们是否等于3 ,如果不相等,则打印它们。

for (Integer i : al)  //for each Integer in the al list
{
  if (!i.equals(3))  //if it is NOT (!) equal to 3
  {
    System.out.println(i);  //then print it
  }
}

Obviously if you want to skip more than just the number 3 you will need to expand the condition the if uses. 显然,如果您要跳过的数字不只是3,则需要扩展if使用的条件。

Note on removing elements from the list 从列表中删除元素的注意事项

If you try and remove from the list within the loop using this method you will encounter problems with ConcurrentAccessException , this is dealt with in this question . 如果您尝试使用这种方法从内环路列表中删除,你会遇到的问题与ConcurrentAccessException ,这是在处理这个问题

If you want to get the list element and as per your output it seems you want to print 1 and even numbers in the list 如果您想获取list元素,并且根据您的输出,似乎您想在列表中打印1甚至偶数

for(int i=0; i< a1.size(); i++)  //iterate over List
{
    if(a1.get(i)%2=0 || a1.get(i) == 1) //print if 1 or even
      System.out.println(a1.get(i));
}

您还可以使用forEach方法(Java 8):

al.forEach(v -> {if(v!=3) System.out.println(v);});

add the required skipping values in a list and check against that list before printing 在列表中添加所需的跳过值,并在打印之前对照该列表进行检查

My code:run and give comment(views please) 我的代码:运行并发表评论(请发表意见)

import java.util.*;
public class Mycode{

 public static void main(String []args){
     ArrayList<Integer> al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(3);
al.add(4);

      ArrayList<Integer> al1 = new ArrayList();
      al1.add(3);
      al1.add(2);
      int flag=0;
      for(int j=0; j< al.size(); j++)
      {
          flag=0;
      for(int i=0; i< al1.size(); i++)
      {
      if(al.get(j)==al1.get(i))
      flag=1;
      }
        if(flag==0)
      System.out.println(al.get(j));
      }
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM