azalut azalut - 1 year ago 64
Java Question

Numbering in some list, Java Streams foreach

I would like to write foreach on some array (that may contains null elements in random places) that will print to the console list of not-null elements with numbering

Lets say I have array called

that contains some Person objects. The result I expect is something like this

1 Name Lastname
2 Name2 Lastname2
3 Name3 Lastname3
and so on..

I know I can do foreach like this: -> n != null).forEach(person -> System.out.print(person.getName() + " " + person.getLastname()));

but this will print not-null objects without ordering number

Name Lastname
Name2 Lastname2
Name3 Lastname3
and so on..

so how to "number" it? since every variable used inside lambda declared outside must be final its impossible to increment it

Answer Source

May not be the best solution, but it's one

    AtomicInteger x=new AtomicInteger(1);
    .filter(n -> n != null)
    .forEach(person -> System.out.print((x.getAndIncrement())+""+person.getName() + " " + person.getLastName()));

If it's acceptable for you using an AtomicInteger, you could do this, being AtomicInteger an immutable class.

Or withouth using any variable, playing a bit with reduce
    .filter(n -> n != null)
    .reduce(1,(a,b)->{System.out.println(a+" "+b.getName() + " " + b.getLastName());return ++a;},(a,b)->{return ++a;});

Notice that inside a lambda expression you're not allowed to modify the object, but you're allowed to modify its state. This is why, in my first example, you can't reassing a new value to x with new keyword, but you can modify its state, i.e. the integer it's wrapping.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download