Home > Software design >  flat elements in arrays with optional, null safe
flat elements in arrays with optional, null safe

Time:10-19

my data structure is

@Data @AllArgsConstructor
class A {
  private B b;
}

@Data @AllArgsConstructor
class B {
  private List<C> cs;
}

@Data @AllArgsConstructor
class C {
  private List<D> ds;
}

@Data @AllArgsConstructor
class D {
  private String value;
}

and all member is nullable. so I want to extract all values(in class D) in this data structure with optional for nullsafe.

I imagine

A a = new A(
  new B(List.of(
    new C(List.of(
      new D("a"), new D("b"), new D("c")
    ))
    , new C(List.of(
      new D("d"), new D("e"), new D("f")
    ))
  ))
);


// it will be List.of("a", "b", "c", "d", "e", "f")
var result = Optional.ofNullable(a)
  .map(A::getB)
  .flatMap(.......)   // <-- i don't know this point how to do to flat elements
  .orElse(List.of("empty")) // or 'orThrow`

CodePudding user response:

I would make every DTO responsible for returning not-null value (either Optional or empty List)

@Data @AllArgsConstructor
class C {
  private List<D> ds;
  public List<D> getDs() {
    return ds == null ? Collections.emptyList() : ds;
  }
}

@Data @AllArgsConstructor
class D {
  private String value;
  public Optional<String> getValue() {
    return Optional.ofNullable(value);
  }
}

CodePudding user response:

Something like this:

var result = Optional.of(a)
        .map(A::getB)
        .map(B::getCs)
        .stream()
        .flatMap(List::stream)
        .filter(Objects::nonNull)
        .map(C::getDs)
        .filter(Objects::nonNull)
        .flatMap(List::stream)
        .filter(Objects::nonNull)
        .map(D::getValue)
        .filter(Objects::nonNull)
        .toList();
  • Related