[英]Java streams, filter based on condition in an object, set value to a string and a an array
I am new to java streams.我是 java 流的新手。 Trying to set 2 values based on a condition inside Java streams.尝试根据 Java 流中的条件设置 2 个值。 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
:你不需要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:您可以在map
方法中创建 object:
ReportInputOptionsExt ext = Arrays.stream(reportInputOptionsExtsElemAgent)
.filter(rgp-> rgp.getKey().equalsIgnoreCase(loadAGENT_ID))
.findFirst()
.map(rgp->new ReportInputOptionsExt(loadAGENT_ID, rgp.getValue()))
.orElse(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.