我有一个这种类型的列表 List<HashMap<String, Object>>
ResultSet 包含对数据库的查询结果。
我想在 List 对象上调用 stream() 。我怎么做 ?
此代码创建我的列表:
public class ResultSetToMap {
int Columns = 0;
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
HashMap<String, Object> row = new HashMap<>();
public List ResultSetToMap(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
while (rs.next()) {
row = new HashMap<String, Object>(columns);
for (int i = 1; i <= columns; ++i) {
row.put(md.getColumnName(i), rs.getObject(i));
}
list.add(row);
}
return list;
}
}
我可以这样查询列表数据:
for (HashMap<String, Object> map : list) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
我想稍后查询这些数据。类型:
films.stream()
.filter(Film.LENGTH.greaterThan(60))
.sorted(Film.TITLE)
.forEach(System.out::println);
最佳答案
除了在 SQL 中更好地过滤和排序数据之外,您还应该使用对象 Film
而不是 Map
:
public class Film {
private String title;
private int length;
// more attributes if you have ...
public Film(String title, int length) {
this.title = title;
this.length = length;
}
public String getTitle() {
return title;
}
public int getLength() {
return length;
}
@Override
public String toString() {
return title + " : " + length;
}
}
现在您可以在创建结果列表时使用它:
public List<Film> getFilmsFromResultSet(ResultSet rs) throws SQLException {
List<Film> result = new ArrayList<>();
while (rs.next()) {
result.add(new Film(rs.getString("TITLE"), rs.getInt("LENGTH")));
}
return result;
}
在 rs.getInt()
和 rs.getString()
方法中使用表中的列名。
像这样使用您的 getFilmsFromResultSet()
方法:
List<Film> films = getFilmsFromResultSet(rs);
films.stream()
.filter(f -> f.getLength() > 60)
.sorted(Comparator.comparing(Film::getTitle))
.forEach(System.out::println);
关于java - 将 List<HashMap<String, Object>> 转换为流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55479399/