java - 使用 Java 8 函数而不是多个 if else

标签 java java-8

我有下面的代码,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;
     }

}

最佳答案

可能是这样,但是 if 语句通常比方法调用便宜,而且对于不了解这些 API 的人来说更容易阅读。您可以考虑的一项改进是:

private Optional<Brand> getBrand(Product p ){
   //...
   //something...
   if (condition) { return Optional.ofNullable(new Brand(p)); }
   else { return Optional.empty(); }
}

然后:

Optional<Brand> brand = getBrand(p);
if (brand.isPresent()) {
  Brand b = brand.get();
}

空值处理更安全。

关于java - 使用 Java 8 函数而不是多个 if else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56068628/

相关文章:

java - 无法使用gson和retrofit从对象读取数据

java - 放大 Java Swing 应用程序

java - Spring WS : How to apply Interceptor to a specific endpoint

Java 将字符串变量作为回调函数传递

java - 使用 lambda 表达式计算偶数的平方

java - Swing中paint、paintComponent和paintComponents的区别

java - 再玩一次功能不起作用

Java lambda 子列表

Java 8 Stream API : how to convert a List to a Map<Long, Set> 在列表中有重复的键?

java - 如何使用 Java 8 流和 lambda 迭代和处理值是元素列表的映射的值