Java流,根据对象中的条件进行过滤,将值设置为字符串和数组

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

我是Java流的新手。尝试根据Java流中的条件设置2个值。我尝试使用平面图。可能做错了。

我要转换为流的工作代码是:

      String NUME_AGENT = "";
      for(int i = 0; i < reportInputOptionsExtsElemAgent.length; i++){
          if(reportInputOptionsExtsElemAgent[i].getKey().equalsIgnoreCase(loadAGENT_ID)){
              NUME_AGENT = reportInputOptionsExtsElemAgent[i].getValue();
              reportInputOptionsExtsElemAgent = new ReportInputOptionsExt[]{new ReportInputOptionsExt(loadAGENT_ID, reportInputOptionsExtsElemAgent[i].getValue())};
          }
      }

我的尝试:

               String NUME_AGENT  = Arrays.stream(reportInputOptionsExtsElemAgent) //not sure about this
              .flatMap(agent -> agent.stream) //not sure about this
              .filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
              .findFirst()
              .map(rgp->rgp.getValue())
              .orElse("");
java filter stream mapping
2个回答
1
投票

您不需要flatMap

 String NUME_AGENT  = Arrays.stream(reportInputOptionsExtsElemAgent)
              //.flatMap(agent -> agent.stream) <---------- you don't need this
              .filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
              .findFirst()
              .map(rgp->rgp.getValue())
              .orElse("");

然后:

reportInputOptionsExtsElemAgent = new ReportInputOptionsExt[]{new ReportInputOptionsExt(loadAGENT_ID, NUME_AGENT  )};

1
投票

您可以在map方法内创建对象:

ReportInputOptionsExt ext  = Arrays.stream(reportInputOptionsExtsElemAgent)
                                        .filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
                                        .findFirst()
                                        .map(rgp->new ReportInputOptionsExt(loadAGENT_ID, rgp.getValue()))
                                        .orElse(null);  

0
投票

这应该工作,首先过滤,然后像在代码中那样提取为数组

reportInputOptionsExtsElemAgent = Arrays.stream(reportInputOptionsExtsElemAgent)
                                .filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
                                .toArray(ReportInputOptionsExt[]::new);
© www.soinside.com 2019 - 2024. All rights reserved.