如何在lambda表达式中抽象方法调用?

问题描述 投票:0回答:1

给出以下两种方法(不是可编译的代码,只是结构):

  protected String mapABC(
    Entity entity, @Context MappingContext mappingContext) {
    return Optional.ofNullable(getSomething(entity))
      .map(
        x ->  getBlah(x::getName))
      .orElse(null);
  }

  protected String mapXYZ(
    Entity entity, @Context MappingContext mappingContext) {
    return Optional.ofNullable(getSomething(entity))
      .map(
        x ->  getBlah(x::getFirstName))
      .orElse(null);
  }

我正在考虑避免重复逻辑时会是什么样子,这样就可以编写类似这样的结构:

protected String mapXYZ(
    Entity entity, @Context MappingContext mappingContext) {
    return xxx(getName());
  }

  protected String mapXYZ(
    Entity entity, @Context MappingContext mappingContext) {
    return xxx(getFirsName());
  }


  private String xxx(Methodreference m){
    return Optional.ofNullable(getSomething(entity))
      .map(
        x ->  getBlah(x::m))
      .orElse(null);
  }

x 的类型是:

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder(toBuilder = true)
public class DetailData {
  private String name;
  private String firstname;
}

我有什么可以尝试的想法吗?

java lambda option-type abstract
1个回答
1
投票

你应该采取

Function<DetailData, String>

private String map(Function<DetailData, String> m){
    return Optional.ofNullable(getSomething(entity))
        .map(
            x -> getBlah(m.apply(x)))
        .orElse(null);
}

用途:

protected String mapXYZ(
    Entity entity, @Context MappingContext mappingContext) {
    return map(DetailData::getName);
}

protected String mapXYZ(
    Entity entity, @Context MappingContext mappingContext) {
    return map(DetailData::getFirstName);
}
© www.soinside.com 2019 - 2024. All rights reserved.