按键值对列表<HashMap <字符串,对象>>排序

时间:2019-04-07 20:41:06

标签: java hashmap

我有一个List < HashMap < String, Object >> ResultSet类型的列表

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;
}

,我想按“ PROBABILITY”键的值对列表值进行排序。 当我打印键和它们的值时,我得到以下信息:

l_commitdate=1996-02-12
l_partkey=155190
PROBABILITY=56.63499683535207
l_commitdate=1996-02-28
l_partkey=67310
PROBABILITY=49.93142590485798
l_commitdate=1996-03-05
l_partkey=63700
PROBABILITY=56.88804620364059
l_commitdate=1996-03-30
l_partkey=2132
PROBABILITY=55.511179358539486

我想得到这个:

l_commitdate=1996-03-05
l_partkey=63700
PROBABILITY=56.88804620364059
l_commitdate=1996-02-12
l_partkey=155190
PROBABILITY=56.63499683535207
l_commitdate=1996-03-30
l_partkey=2132
PROBABILITY=55.511179358539486
l_commitdate=1996-02-28
l_partkey=67310
PROBABILITY=49.93142590485798

2 个答案:

答案 0 :(得分:0)

假定概率值的类型为double:

list.sort((p1,p2)-> Double.compare( (double)p2.get("PROBABILITY"),(double) p1.get("PROBABILITY")));

答案 1 :(得分:0)

似乎您知道ResultSet中每一行的结构,因此,如果创建一个对象来代表每一行而不是使用Map<String, Object>,事情将会变得容易得多。我称它为Part,因为这似乎是该键所要指的,但是只要有意义就可以称之为它。

public class Part {
    private LocalDate commitDate;
    private long partKey;
    private BigDecimal probability;

    //getters and setters
}

使用此方法,您可以更改方法以返回Part的列表(顺便说一句:您不应在此处使用无类型的列表。即使您不遵循我的建议,您的方法签名应始终具有返回的List的类型Java方法名称也应以小写字母开头-按照惯例,只有class的名称以大写)。

public List<Part> resultSetToParts(ResultSet rs) throws SQLException {
    List<Part> list = new ArrayList<>(); //No need to specify the generic type again, we can use the diamond operator for Java 7 and later

    while (rs.next()) {
        Part part = new Part();

        part.setCommitDate(rs.getDate("l_commitdate").toLocalDate()); //Note: this is vulnerable to NullPointerExceptions if the date can be null
        part.setPartKey(rs.getString("l_partkey"));
        part.setProbability(BigDecimal.valueOf(rs.getDouble("PROBABILITY")));

        list.add(part);
    }
    return list;
}

现在我们已经完成了少量工作来进行设置,您可以非常轻松地按所需的任何字段对其进行排序:

List<Part> parts = resultSetToParts(rs);
parts.sort(Comparator.comparing(Part::getProbability);