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

Java 如何将以下代码转换为lamda表达式,java,Java,有多种方法: publicmap do(Tr请求){ Map res=新的HashMap(); List=req.getSome(); 如果(空!=列表){ 适用于(Spp sp:列表){ 如果(“op1”.equals(sp.getKey())){ res.put(“op1”,sp.getValue()); } 如果(“op2”.equals(sp.getKey())){ res.put(“op2”,sp.getValue()); } 如果(“op3”.equals(sp.getKey()))

有多种方法:

publicmap do(Tr请求){
Map res=新的HashMap();
List=req.getSome();
如果(空!=列表){
适用于(Spp sp:列表){
如果(“op1”.equals(sp.getKey())){
res.put(“op1”,sp.getValue());
}
如果(“op2”.equals(sp.getKey())){
res.put(“op2”,sp.getValue());
}
如果(“op3”.equals(sp.getKey())){
res.put(“op3”,sp.getValue());
}
}
}
返回res;
}
if(“op1.equals(sp.getKey())){
res.put(“op1”,sp.getValue());
}
重复部件想转换lamda,不知道使用什么功能

需要帮忙吗,谢谢

试试这个

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));
}
static final Set KEY_SELECTION=Set.of(“op1”、“op2”、“op3”);
公共地图剂量测量(Tr要求){
返回可选的.ofNullable(req.getSome())
.orElse(Collections.emptyList())
.stream()
.filter(sp->KEY\u SELECTION.contains(sp.getKey()))
.collect(Collectors.toMap(Spp::getKey,Spp::getValue));
}

我可以建议另一种方法,因为您要求提供功能界面(大致基于@saka1029-answer,他的答案比我的好得多)

定义双消费函数双消费函数

  private static <T, U> void resolve(T t, U u, BiConsumer<T, U> biConsumer) {
    biConsumer.accept(t, u);
  }
私有静态无效解析(T T、U U、双消费双消费){
双消费者接受(t,u);
}
并对方法进行更改(顺便说一句,do在java中是一个保留关键字,因此不接受它作为方法名)

公共静态映射do1(Tr请求){
Map res=新的HashMap();
List=req.getSome();
集合运算=集合运算(“op1”、“op2”、“op3”);
如果(空!=列表){
适用于(Spp sp:列表){
解决(res,sp,
(res1,sp1)->{
if(operation.contains(sp.getKey())){
res.put(sp.getKey(),sp.getValue());
}
});
}
}
返回res;
}

到目前为止,您尝试了什么?你被困在哪里?@NicoHaase在一个循环中有多个判断吗?@cheng.pro为什么你需要这里的流。for循环看起来很干净。@守护进程,因为许多类都有这样的代码,并且希望删除重复。@守护进程的区别在于比较的字符串不同。
  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;
  }