Home > Mobile >  Iterate the non-null elements of an array
Iterate the non-null elements of an array

Time:05-03

I have an Array in Java with several elements, what I am doing is Iterating and displaying all the elements of the Array that are different from null.

This is the Demo:

public class TestData {

    public static void main(String[] args) {

        String firstArg[] = new String[5];
        firstArg[2] = "arg2";
        firstArg[4] = "arg4";
        
        for (String a: firstArg) {
            if (a != null) {
                System.out.println(a);
            }            
        }
    }    
}

My problem: is it possible to iterate the elements other than null in a single line?

CodePudding user response:

public class TestData {
  public static void main(String[] args) {
    String firstArg[] = new String[5];
    firstArg[2] = "arg2";
    firstArg[4] = "arg4";
    
    Stream.of(firstArg)
      .filter(Objects::nonNull)
      .forEach(System.out::println);
  }    
}

Instead of .filter(Objects::nonNull) you could use .filter(s->s!=null).

If you want to do more than just printing, you could use

  .forEach(s->{
    // Do something more with 's'
    System.out.println(s.toUpperCase());
  });

See also Filter values only if not null using lambda in Java8

CodePudding user response:

You can first remove all null from your array:

Yourlist.removeAll(Collections.singleton(null));

And then iterate

  • Related