2017-03-16 58 views
1

我有下面的代码片段Java流遍历ResultSet对象

ResultSet rs = stmt.executeQuery(); 
List<String> userIdList = new ArrayList<String>(); 
while(rs.next()){ 
    userIdList.add(rs.getString(1)); 
} 

我可以使用Java流/ Lambda表达式来执行本次迭代,而不是一个while循环来填充列表?

+2

' Stream的工厂方法,因为“迭代直到next()'返回false”,所以你运气不好。“Java 8中不能用它们表示逻辑。Java 9中将支持这种方法,但是,checke d'SQLException'阻止您编写简洁的lambda表达式。你很可能最终会得到一个自定义的'Spliterator',就像在[这个答案](http://stackoverflow.com/a/32232173/2711488)中一样,它涵盖的不仅仅是迭代ResultSet。当你经常使用它时,这对工厂是有用的,但是对于转换单个循环来说,这将是过度的。 – Holger

回答

2

您可以为ResultSet创建一个包装,使其成为Iterable。从那里你可以迭代以及创建一个流。当然,你必须定义一个映射函数来获得结果集中的迭代值。

ResultSetIterable可能看起来像这样

public class ResultSetIterable<T> implements Iterable<T> { 

    private final ResultSet rs; 
    private final Function<ResultSet, T> onNext; 

    public ResultSetIterable(ResultSet rs, Function<ResultSet, T> onNext){ 
    this.rs = rs; 
    //onNext is the mapper function to get the values from the resultSet 
    this.onNext = onNext; 
    } 


    @Override 
    public Iterator<T> iterator() { 

    try { 
     return new Iterator<T>() { 

      //the iterator state is initialized by calling next() to 
      //know whether there are elements to iterate 
      boolean hasNext = rs.next(); 

      @Override 
      public boolean hasNext() { 
       return hasNext; 
      } 

      @Override 
      public T next() { 

       T result = onNext.apply(rs); 
       //after each get, we need to update the hasNext info 
       try { 
        hasNext = rs.next(); 
       } catch (SQLException e) { 
        //you should add proper exception handling here 
        throw new RuntimeException(e); 
       } 
       return result; 
      } 
     }; 
    } catch (Exception e) { 
     //you should add proper exception handling here 
     throw new RuntimeException(e); 
    } 
    } 

    //adding stream support based on an iteratable is easy 
    public Stream<T> stream() { 
    return StreamSupport.stream(this.spliterator(), false); 
    } 
} 

现在,我们有我们的包装,你可以流过的结果:如果你想使用一个

ResultSet rs = stmt.executeQuery(); 
List<String> userIdList = new ResultSetIterable(rs, rs -> rs.getString(1)).stream() 
                      .collect(Collectors.toList()) 

}

+0

或者你可以使用'org.apache.commons.dbutils.ResultSetIterator.iterable(rowSet)' –