I have translated a code from Matlab (array orientation) to Java(OOP). The problem appeared when I have to translate this feature of Matlab:
min_omegaF_restricted=min(omegaF(p>cost));
Here, omegaF
is a vector with the net worth of each firm. p
a vector of prices for each firm. cost
a vector of costs for each firm. The above calculate the minimal net worth of survivor firms with demanded price higher than their costs. In java can be translated to:
double min_omegaF_restricted=Double.POSITIVE_INFINITY;
for(int f=0; f<F; f++){
Firm fo=firms.get(f);
if(fo.p>fo.cost)
min_omegaF_restricted=Math.min(min_omegaF_restricted, fo.omegaF);
}
Is there a option to generalize this kind of sentence to whatever condition ( fo.p>fo.cost
)?
Yes. Functional interfaces and lambdas in Java 8 make this simple and easy on the eyes. Create a Predicate which tests an object and returns a boolean value.
Predicate<Firm> predicate = firm -> firm.p > firm.cost;
Then you can defer to the predicate in the loop like so:
double min_omegaF_restricted=Double.POSITIVE_INFINITY;
for(int f=0; f<F; f++){
Firm fo=firms.get(f);
if(predicate.test(fo))
min_omegaF_restricted=Math.min(min_omegaF_restricted, fo.omegaF);
}
What's more, with the new streaming API you can express the whole computation functionally without the explicit for
loop.
double min_omegaF_restricted = firms.stream()
.filter(predicate)
.mapToDouble(f -> f.omegaF)
.min()
.orElse(Double.POSITIVE_INFINITY);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.