0

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?

  • 3
    (edited, first try was wrong) Your loop can be replaced with `Arrays.stream(firstArg).filter(Objects::nonNull).forEach(System.out::println);` – Michel K May 02 '22 at 19:02
  • @MichelK What I want is to iterate the same as I am doing but over the elements that are not null, to avoid including an if inside. The sysout is not needed on the same line. I had never seen this way of doing it and I don't understand very well. – prueba once May 02 '22 at 19:04
  • you can read this quick tutorial on the stream API https://www.baeldung.com/java-8-streams Michael used the stream api to filter out non nulls and print each item in the stream after filtering. The double colon operator is a shorthand for calling methods in lambdas: https://www.baeldung.com/java-8-double-colon-operator – Quy May 02 '22 at 19:09
  • @pruebaonce there's no such thing as `for(String a: firstArg.whereNotNull())`. You need that `if` in the loop. You can extract that filtering to another method so it returns only non-null objects, but you have to do it. – ernest_k May 02 '22 at 19:09
  • I don't think there's a nice way to do this without using an `if`. Note that you can replace the `System.out::println` with a lambda of the form `a -> { System.out.println(a); }`, but it will still be a `.forEach`. – Michel K May 02 '22 at 19:10

2 Answers2

1
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

YoYo
  • 9,157
  • 8
  • 57
  • 74
0

You can first remove all null from your array:

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

And then iterate

Evyatar Cohen
  • 292
  • 1
  • 9
  • 25