I'm trying to compare the end results of a series operations on two variables. Since operations are the same, I use java stream on these two variables. But I need to return the results based on the sub-variables of the objects. For example:
class MyClass {
String strVal;
Integer intVal;
}
MyClass myFunction(MyClass myClass1, MyClass myClass2) {
Stream.of(myClass1, myClass2)
.map(function) // get intVal for both objects
.filter(predicate)
...
// return myClass1 if myClass1.intVal > myClass2.intVal, otherwise myClass2
// current implementation
return myClass1.intVal > myClass2.intVal ? myClass1 : myClass2;
}
Are there ternary operator equivalent that can be used in stream? Maybe need to create new Functional Interfaces?
The reason why I'm asking is that this is not the only place in the code to get the value based on the comparison results. Some places I need to use a function like
return myClass1.intVal > myClass2.intVal ? function(myClass1) : function(myClass2);
I understand how stream is implemented, like the comment section mentioned below. But the whole concept is to make the code cleaner. So if there's a cleaner way to return the value with only one function, it's better than repeating the function for all variables.
When comparing just 2 elements I stick to ternary operator, but if you really want to use streams, then you could do it by using the .max() method passing it a comparator in which you define which object is greater based on your policy (in this case who has the bigger intVal), like this:
MyClass myFunction(MyClass myClass1, MyClass myClass2) {
// return myClass1 if myClass1.intVal > myClass2.intVal, otherwise myClass2
return Stream.of(myClass1, myClass2)
.max((m1, m2) -> m1.intVal.compareTo(m2.intVal))
.get();
}
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