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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.