我是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("");
您不需要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 )};
您可以在map
方法内创建对象:
ReportInputOptionsExt ext = Arrays.stream(reportInputOptionsExtsElemAgent)
.filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
.findFirst()
.map(rgp->new ReportInputOptionsExt(loadAGENT_ID, rgp.getValue()))
.orElse(null);
这应该工作,首先过滤,然后像在代码中那样提取为数组
reportInputOptionsExtsElemAgent = Arrays.stream(reportInputOptionsExtsElemAgent)
.filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
.toArray(ReportInputOptionsExt[]::new);