Dhiresh Budhiraja
Dhiresh Budhiraja

Reputation: 2705

Pass Two Parameters In a function using lambda

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());
}

Upvotes: 3

Views: 4944

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170735

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()));

Upvotes: 1

Eran
Eran

Reputation: 393821

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.

Upvotes: 4

Related Questions