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

How to abstract method call in lamba expression?

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

  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;
}

有什么想法可以尝试吗?

你应该参加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);
}