3

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)
Neuron
  • 5,141
  • 5
  • 38
  • 59
Don_Quijote
  • 936
  • 3
  • 18
  • 27

3 Answers3

8

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)
user2357112
  • 260,549
  • 28
  • 431
  • 505
0

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

Brian
  • 1,659
  • 12
  • 17
  • But why this: a = {1, 2, 3} map(lambda x: print(x), a) - won't print anything? – Don_Quijote Jun 09 '16 at 16:53
  • 1
    See this SO question: http://stackoverflow.com/questions/7731213/print-doesnt-print-when-its-in-map-python I hope it answers your question :) – Brian Jun 09 '16 at 17:00
  • @Don_Quijote map returns a new list with the same number of elements as the original list. The print function does however not return something. So it is not possible to create this new list. – Matthias Jun 09 '16 at 17:01
  • @Don_Quijote you could however create a new function def custom_print(x): print(x); return x with side effects and then use map(custom_print, a) But I rather don't advise such practices – Matthias Jun 09 '16 at 17:04
0

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)