如何将以下代码转换为lamda表达式

时间:2020-08-10 09:19:25

标签: java

有很多方法:

   public Map<String,String> do(Tr req){
       Map<String,String> res=new HashMap<>();
       List<Spp> list=req.getSome();
       if(null!=list) {
           for (Spp sp : list) {
               if ("op1".equals(sp.getKey())) {
                   res.put("op1", sp.getValue());
               }
               if ("op2".equals(sp.getKey())) {
                   res.put("op2", sp.getValue());
               }
               if ("op3".equals(sp.getKey())) {
                   res.put("op3", sp.getValue());
               }
           }
       }
       return res;
    }
if ("op1".equals(sp.getKey())) {
      res.put("op1", sp.getValue());
}

重复部分想转换lamda,不知道要使用什么功能

想要一些帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

尝试一下。

static final Set<String> KEY_SELECTION = Set.of("op1", "op2", "op3");

public Map<String, String> doSomething(Tr req) {
    return Optional.ofNullable(req.getSome())
        .orElse(Collections.emptyList())
        .stream()
        .filter(sp -> KEY_SELECTION.contains(sp.getKey()))
        .collect(Collectors.toMap(Spp::getKey, Spp::getValue));
}

答案 1 :(得分:0)

我可以建议另一种方法,因为您已经要求功能接口(大致基于@ saka1029的答案,他的答案比我的要好得多)。

定义BiConsumer biConsumer函数

  private static <T, U> void resolve(T t, U u, BiConsumer<T, U> biConsumer) {
    biConsumer.accept(t, u);
  }

并在您的方法中进行如下更改(顺便说一句,do是java中的保留关键字,因此它不被接受为方法名称)

  public static Map<String, String> do1(Tr req) {
    Map<String, String> res = new HashMap<>();
    List<Spp> list = req.getSome();
    Set<String> operation = Set.of("op1", "op2", "op3");
    if (null != list) {
      for (Spp sp : list) {
        resolve(res,sp,
            (res1, sp1) -> {
              if (operation.contains(sp.getKey())) {
                res.put(sp.getKey(), sp.getValue());
              }
            });
      }
    }
    return res;
  }