【发布时间】:2019-05-09 23:02:06
【问题描述】:
我有下面的代码,getBrand 和 calculateSum 是一些返回值的函数。我想使用 java 8 函数压缩这段代码。如果可能的话,我想摆脱多个如果。是否可以使用 Java 8 函数?
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Q56068628 {
static class Brand {
public Set<Location> locations() { return Collections.emptySet(); }
}
static class Location {}
static class Product {}
int getSum(int price, Product p){
int sum = 0;
if(price > 0){
Brand b = getBrand(p); // getBrand takes type Product as argument
if( b !=null){
Set<Location> s = new HashSet<>();
s.addAll(b.locations());
for(Location l : s){
sum = calculateSum(l, sum); /* calculateSum function takes location
argument and calculates sum. Sum value is replaced for
each for loop call */
}
}
}
return sum;
}
private Brand getBrand(Product p ){
//// some code returns brand
return null;
}
private int calculateSum(Location l, int sum ){
//// some code returns an integer
return 0;
}
}
【问题讨论】:
-
如果您只需要使用最后一个位置的
sum,为什么要遍历整个集合?以及为什么将sum传递给calculateSum,当它在每个循环中被替换时。