Guava Optional type, when transformation returns another Optional

前端 未结 3 1015
南方客
南方客 2021-01-20 01:42

I have a method that procudes an Optional

But this String must be parsed at another application level as Integer or Long.

This I h

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 01:52

    I guess you can do:

    public static void main(final String[] args) {
      final Optional valid = Optional.of("42")
          .transform(STR_TO_INT_FUNCTION)
          .or(Optional.absent());
      System.out.println(valid); // Optional.of(42)
      final Optional invalid = Optional.of("Toto")
          .transform(STR_TO_INT_FUNCTION)
          .or(Optional.absent());
      System.out.println(invalid); // Optional.absent()
      final Optional absent = Optional.absent()
          .transform(STR_TO_INT_FUNCTION)
          .or(Optional.absent());
      System.out.println(absent); // Optional.absent()
    }
    
    private static final Function> STR_TO_INT_FUNCTION =
        new Function>() {
          @Override
          public Optional apply(final String input) {
            return Optional.fromNullable(Ints.tryParse(input));
          }
        };
    

    Usage isn't that clumsy when you use Optional -> transform -> or in one line (assigning transformed optional integer would produce Optional>).

提交回复
热议问题