I am new to java streams. Trying to set 2 values based on a condition inside Java streams. I tried using flatmap. Probably doing something wrong.
The working code which i want to convert to streams is:
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())
};
}
}
My attempt:
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("");
you don't need the 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("");
and then:
reportInputOptionsExtsElemAgent = new ReportInputOptionsExt[]{new ReportInputOptionsExt(loadAGENT_ID, NUME_AGENT )};
You can create the object inside the map
method:
ReportInputOptionsExt ext = Arrays.stream(reportInputOptionsExtsElemAgent)
.filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
.findFirst()
.map(rgp->new ReportInputOptionsExt(loadAGENT_ID, rgp.getValue()))
.orElse(null);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.