Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Java forEach equivalent

I am Java programmer. I started learning Python few days ago. I'm wondering: are there any equivalents to

map.forEach(System.out::println)

in Python with lambdas? Or only with for loop:

for e in map: print(e)
like image 224
Don_Quijote Avatar asked Jan 24 '26 09:01

Don_Quijote


1 Answers

There is no equivalent to Java's imperative Iterable.forEach or Stream.forEach method. There's a map function, analogous to Java's Stream.map, but it's for applying transformations to an iterable. Like Java's Stream.map, it doesn't actually apply the function until you perform a terminal operation on the return value.

You could abuse map to do the job of forEach:

list(map(print, iterable))

but it's a bad idea, producing side effects from a function that shouldn't have any and building a giant list you don't need. It'd be like doing

someList.stream().map(x -> {System.out.println(x); return x;}).collect(Collectors.toList())

in Java.

The standard way to do this in Python would be a loop:

for thing in iterable:
    print(thing)
like image 83
user2357112 supports Monica Avatar answered Jan 26 '26 23:01

user2357112 supports Monica