【问题标题】:Return value if not null如果不为空则返回值
【发布时间】:2020-08-09 05:03:36
【问题描述】:

我试图写尽可能少的行。 用Java重写它的最佳方法是什么? (假设我们有一个“公共枚举 A”)

我想有一种写法“如果某些东西不为空,则返回它,否则,继续”。 我查看了 Optional,但 Optional.of(...).ifPresent( v -> return v;) 不起作用,尽管我希望它起作用。

另外,如果你问我为什么要在 for 循环中更改数组,你可以认为有多个初始数组,我需要分别测试它们。

public A getAValue() {
   int[] arr = new int[7];
   A returnValue = null;

   for (int i=0; i<10; i++) {

      //change arr
      returnValue = checkSomeCondition(arr);
      if (returnValue != null) {
         return returnValue;
      }

      //change arr again
      returnValue = checkSomeCondition(arr);
      if (returnValue != null) {
         return returnValue;
      }

      //change arr yet again
      returnValue = checkSomeCondition(arr);
      if (returnValue != null) {
         return returnValue;
      }
   }


   return A.UNKNOWN;
}

public A checkSomeCondition(int[] arr) {
   if (arr[0]==arr[1]) {
      return arr[0]==2 ? A.VALUE_1 : A.VALUE_2;
   }

   return null;
}

【问题讨论】:

  • 感谢您的帮助。我会研究解决方案。同时,这里是代码:github.com/imosescu/XsiO。这是一个井字游戏:)

标签: java java-8 optional


【解决方案1】:

不清楚您在做什么样的测试或如何更改您的数组
但这可能是可能的:

这应该忽略所有null 返回值,只返回
first successful 测试结果。

如果没有成功,则必须提供 default 返回对象。

enum A {
    A_VALUE_1, A_VALUE_2, A_UNKNOWN
};

List<Object[]> testArrays = new ArrayList<>();
testArrays.add(new int[] { 1, 2, 3 });
testArrays.add(new int[] { 3, 4, 5 });
testArrays.add(new int[] { 2, 2, 6 });

A res =
        // stream the set of arrays   
        testArrays.stream()

        // apply each set in order to the method
        // replacing the array under test with the
        // method result
        .map(arr->checkSomeCondition(arr))

         // filter out any null results
         .filter(result->result!=null)

         // get the first non-null result
         .findFirst()

         // return the result or some default answer if all
         // results were null.
         .orElseGet(()->A.A_UNKNOWN);

System.out.println(res);

使用提供的数据,打印

A_VALUE_1

你的测试方法


public A checkSomeCondition(int[] arr) {
    if (arr[0] == arr[1]) {
        return arr[0] == 2 ? A.A_VALUE_1 : A.A_VALUE_2;
    }

    return null;
}

不利的一面是它要求您提供一个数组数组,如果先前的测试失败,则在其中使用后续数组。您可以根据您的要求调整概念。

【讨论】:

    【解决方案2】:

    问:我查看了 Optional,但 Optional.of(...).ifPresent(v -> return v;) 不起作用,虽然我希望它起作用

    Optional::ifPresent 有效,但与预期不同。 returnConsumer 的方法实现中。而且Consumer不返回任何东西,方法返回类型是void

    问:我试图写尽可能少的行。

    借助一组预定义的数组供应商Supplier&lt;int[]&gt; 和现有循环中的另一个 for 循环,您可以实现您想要的,其迭代次数与条件数相同。

    List<Supplier<int[]>> arrays = new ArrayList<>();
    arrays.add(() -> firstArraySource());
    arrays.add(() -> secondArraySource());
    ...
    
    for (...) {                                         // your initial loop
        for (Supplier<int[]> arraySupplier: arrays) {   // iterate through Suppliers
            arr = arraySupplier.get();                  // get an array (here is the evaluation)
            returnValue = checkSomeCondition(arr);      // getting the 'A' value
            if (returnValue != null) {                  // returnin if not null
                return returnValue;
            }
        }
    }
    

    这种方法的优点是,如果数组的来源是 ex.从数据库中,它们不会在之前被调用,因为它们被包装在供应商中。计算发生在调用 Supplier::get 时。

    【讨论】:

      【解决方案3】:

      使用Optional.ofNullable 而不是Optional.of,因为后者不能用于可能的空值。这将起作用,并将该任务委托给checkSomeCondition 函数:

      public Optional<A> checkSomeCondition(int[] arr) {
          if (arr[0] == arr[1]) {
              return Optional.<A>of(arr[0]==2 ? A.VALUE_1 : A.VALUE_2);
          }
          return Optional.<A>empty();
      }
      

      ...然后检查 getAValue 中是否存在值。

      然后可以在循环中检查条件,即

      public A getAValue() {
          int[] arr = new int[7];
          final int maxChecks = 10;
          Optional<A> returnValue = Optional.<A>empty();
      
          for (int i = 0; i < 10; i++) {
              int j = 0;
              while (!returnValue.isPresent() && j < maxChecks) {
                   returnValue = checkSomeCondition(arr);
                   j++;
              }
              return returnValue.get();
          }
          return A.UNKNOWN;
      }
      

      【讨论】:

      • 使用 Optional 很好,但 OP 仍然必须具有相同的结构,因此它不会减少代码。
      猜你喜欢
      • 1970-01-01
      • 2014-02-07
      • 2021-04-29
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      相关资源
      最近更新 更多