Java 8 added lambda expressions. Using lambdas in a similar fashion to anonymous classes is pretty straight forward, but I'm wondering if the related functionality of using named functions as arguments to other functions exists. For example, is there a Java way to write the following Python code:
list1 = (1,2,3)
list2 = (4,5,6)
def add(a, b):
return a+b
for e in map(add, list1, list2):
print(e)
output
5
7
9
Yes, you can use method references like Integer::sum
where lambdas are allowed.
int six = IntStream.of(1, 2, 3)
.reduce(0, Integer::sum);
This is equivalent to
int six = IntStream.of(1, 2, 3)
.reduce(0, (a, b) -> Integer.sum(a, b));
Methods like Integer.sum
and Double.max
were added in Java 8 precisely so they could be used in lambdas like this.
There's no built-in way to "zip" together multiple lists the way Python does, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With