Jose Pinho
Jose Pinho

Reputation: 33

Is it possible to use methods inside String format to use in java streams?

Is it possible to convert code like this

for (Contacto contact : contactos) {
    fix.printf("%s\t%s\t%s\n", 
        contact.getName(), contact.getNumb(), contact.getDateOfBirth());
}

into a java stream?

Upvotes: 0

Views: 84

Answers (1)

hnefatl
hnefatl

Reputation: 6037

Sure you can - the below should do the trick, using the forEach method of Stream:

contactos.stream()
         .forEach(c -> fix.printf("%s\t%s\t%s\n", c.getName(), c.getNumb(), c.getDoB()));

Bear in mind this can impair readability - most people I know would say the loop is easier to read than this.

Also bear in mind that reaaaaally, for this, you should use forEachOrdered instead of forEach - forEach doesn't guarantee the order in which the items are processed, and for parallel streams this matters. forEachOrdered guarantees that items are processed one-by-one.


You can omit the call to Stream, depending on your container - if it implements Iterable (most standard containers do), then you should use forEach on that rather than the stream (so contactos.forEach(...). It's tidier and avoids the overhead of creating a Stream.

You also avoid the forEachOrdered issue above, as the items are processed "in iteration order".

Upvotes: 2

Related Questions