Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing named functions as arguments

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
like image 230
ewok Avatar asked Apr 30 '15 21:04

ewok


Video Answer


1 Answers

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.

like image 76
John Kugelman Avatar answered Sep 17 '22 23:09

John Kugelman