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