3

I am very new to lambdas in Java.

I have started using it as i found them quite interesting but i still don't know how to use them completely

I have a list of uuids and for each uuid i want to call a function which takes two parameters : first is a string and second is uuid

I am passing a constant string for each uuid

I have written a following code but its not working

uuids.stream()
     .map(uuid -> {"string",uuid})
     .forEach(AService::Amethod);

It is method which is another class AService

public void Amethod(String a, UUID b) {
    System.out.println(a+b.toString());
}
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Dhiresh Budhiraja
  • 2,575
  • 5
  • 17
  • 26
  • 1
    Possible duplicate of [Can a java lambda have more than 1 parameter?](https://stackoverflow.com/questions/27872387/can-a-java-lambda-have-more-than-1-parameter) – Feras Al Sous Oct 30 '17 at 10:30

2 Answers2

4

A lambda expression has a single return value, so {"string",uuid} doesn't work.

You could return an array using .map(uuid -> new Object[]{"string",uuid}) but that won't be accepted by your AService::Amethod method reference.

In your example you can skip the map step:

uuids.stream()
     .forEach(uuid -> aservice.Amethod("string",uuid));

where aservice is the instance of AService class on which you wish to execute the Amethod method.

Eran
  • 387,369
  • 54
  • 702
  • 768
1
uuids.stream().forEach(uuid -> AService.Amethod("string", uuid));

You can write something closer to your current code given a Pair class, but 1) you end up with more complicated code; 2) Java standard library doesn't have one built-in. Because of 2), there are quite a few utility libraries which define one. E.g. with https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html, it would be

uuids.stream()
        .map(uuid -> Pair.of("string",uuid))
        .forEach(pair -> AService.Amethod(pair.getLeft(), pair.getRight()));
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487