【问题标题】:Set value to a string variable, from an object based on the condition using Java Streams使用 Java Streams 根据条件从对象将值设置为字符串变量
【发布时间】:2020-05-11 13:23:57
【问题描述】:

我是 Java 流的新手。我有一个需要使用 java 流编写的代码 sn-p。我正在尝试根据条件为字符串设置一个值。我试图寻找解决方案并使用 anyMatch 进行试验,但无法获得任何结果。

String loadAGENTID = "";
for(ReportGenerationParameter rgp : loadReportTableExt.getReportGenerationParameters()) {
    if (rgp.getKey().equalsIgnoreCase(RapFilter.IDUSR)) {
        loadAGENT_ID = rgp.getValue();
    }
}

字符串 loadAGENTID 将在代码中使用。欢迎任何建议。谢谢。

我尝试过使用Arrays.streamanyMatch,但到目前为止没有运气

boolean todoName =
        Arrays.stream(loadReportTableExt.getReportGenerationParameters())
              .anyMatch(item -> item.getKey().equalsIgnoreCase(RapFilter.IDUSR));

if (todoName) {
    // want to set the value of the respective object.
    loadAGENT_ID = item.getValue();
}

【问题讨论】:

    标签: java java-stream


    【解决方案1】:

    使用filter查找匹配对象,然后使用findFirst返回第一个匹配元素

    String loadAGENTID  = loadReportTableExt.getReportGenerationParameters()
                                            .stream()
                                            .filter(rgp-> rgp.getKey().equalsIgnoreCase(RapFilter.IDUSR))
                                            .findFirst()
                                            .map(rgp->rgp.getValue())   // returns value from first matching element 
                                            .orElse("");  // none of them matched returns default value
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-27
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 2020-07-23
      • 2019-07-28
      相关资源
      最近更新 更多