【问题标题】:Java streams, filter based on condition in an object, set value to a string and a an arrayJava 流,根据对象中的条件进行过滤,将值设置为字符串和数组
【发布时间】:2020-08-27 04:48:27
【问题描述】:

我是 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 java-stream mapping


    【解决方案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);  
    

    【讨论】:

      【解决方案2】:

      你不需要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  )};
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-15
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        相关资源
        最近更新 更多