【问题标题】:How to replace the for each using streams in java如何在 java 中替换 for each using streams
【发布时间】:2022-12-12 13:24:23
【问题描述】:
Dates.forEach(date -> {
            executeQuery(date, loads);
            
private void executeQuery(LocalDate date, ArrayList<Load> loads){
        MapSqlParameterSource source = new MapSqlParameterSource();
            source.addValue("date", date.toString());
            Load load = namedJdbcTemplate.queryForObject(Constants.SQL_QUERY, source,
                    new BeanPropertyRowMapper<>(Load.class));
            loads.add(load);
}

如何将流概念用于上述代码

【问题讨论】:

    标签: java spring foreach java-8 java-stream


    【解决方案1】:

    这样的事情应该工作

    // change your method like so            
    private Load executeQuery(LocalDate date){
        MapSqlParameterSource source = new MapSqlParameterSource();
        source.addValue("date", date.toString());
        return namedJdbcTemplate.queryForObject(Constants.SQL_QUERY, source,
            new BeanPropertyRowMapper<>(Load.class));
    }
    
    // load your dates from somewhere
    List<LocalDate> dates = getYourDates(); 
    // now use the streams API to collect the query results into a new list
    List<Load> loads = dates.stream()
      .map(this::executeQuery)
      .collect(Collectors.toList());
    

    或者

    List<Load> loads = getYourDates().stream()
      .map(this::executeQuery)
      .collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 2022-01-23
      • 2011-07-21
      相关资源
      最近更新 更多