Reputation: 1474
I want to rewrite the below for-loop-statement by lambda expression of java8.
public class Test {
List<ObjectTest> lst;
public int operation(int a, int b) {
return a * b;
}
int max = 0;
ObjectTest suitableObj = null;
for(ObjectTest obj:lst) {
int result = operation(obj.getA(), obj.getB());
if(result > max) {
suitableObj = obj;
max = result;
}
}
}
How is it possible by lambda expression?
Upvotes: 2
Views: 94
Reputation: 3191
@Eran's answer is the most concise, but you should consider writing an overloaded method:
public int operation(ObjectTest o) {
return o.getA() * o.getB();
}
Then you could simply write:
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.maxBy;
list.stream().max(comparing(Test::operation)).orElse(null);
to obtain the object for which operation yields the maximum result, and
list.stream().maToInt(comparing(Test::operation)).max().orElse(0);
to obtain the the maximum result.
Upvotes: 0
Reputation: 393856
You can Stream
your ObjectTest
elements, map them to an IntStream
and call the max()
method to compute the maximum value:
int max = lst.stream()
.mapToInt(obj->operation(obj.getA(), obj.getB()))
.max()
.orElse(0); // default value in case the input List is empty
EDIT: If you want, after your edit, to find the ObjectTest
instance having the max value of operation(obj.getA(), obj.getB())
, you can use Stream
's max(Comparator<? super T> comparator)
:
ObjectTest max = lst.stream()
.max(Comparator.comparingInt(obj->operation(obj.getA(), obj.getB())))
.orElse(null);
Upvotes: 7