【问题标题】:Convert clause for with Set<Map<String, Object>> to clause forEach将 Set<Map<String, Object>> 的子句转换为 forEach 子句
【发布时间】:2016-09-28 15:23:48
【问题描述】:

我有以下方法:

protected Set<Map<String, Object>> joinQueryResults(Set<Map<String, Object>> resultEmpty, Set<Map<String, Object>> resultWithValues){
    for(Map<String, Object> mapEmpty: resultEmpty){         
        for(Map<String, Object> mapValue: resultWithValues){
            if (mapValue.get("name").equals(mapEmpty.get("name"))){
                mapEmpty.replace("totfailed", mapValue.get("totfailed"));
                mapEmpty.replace("totsuccess", mapValue.get("totsuccess"));
                break;
            }       
        }   
    }       
    return resultEmpty; 
}

如何将其转换为 forEach 子句?有可能吗?

【问题讨论】:

    标签: for-loop foreach java-8


    【解决方案1】:

    不赞成在流中更新共享可变变量。应该这样做。

    resultEmpty.stream().forEach(empty -> {
      resultWithValues.stream()
          .filter(
              withValues -> withValues.get("name").equals(empty.get("name")))
          .findFirst().ifPresent(withValues -> {
            empty.replace("totsuccess", withValues.get("totsuccess"));
            empty.replace("totfailed", withValues.get("totfailed"));
          });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 2014-01-29
      • 2015-11-21
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多