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)
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)
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)
Python also has a map
function and it uses the syntax map(function, iterable, ...)
See Python docs: https://docs.python.org/2/library/functions.html#map
Unfortunately there is no built-in stream like in Java, but if you are willing to use an external library, PyStreamAPI (https://github.com/PickwickSoft/pystreamapi) does for Python what Java Stream API does in Java.
Your code could look like that:
from pystreamapi import Stream
Stream.of(map).for_each(print)