簡體   English   中英

Java Mybatis結果到Hashmap

[英]Java Mybatis result to Hashmap

PSQL 查詢返回 2 個值名稱和計數的列表。

我想把它放到一個 Hashmap 並返回值。

查詢結果會像

name        count
completed   2
successful  8
inprogress  1

我能夠在結果變量中得到結果。 但是在 for 循環中,我得到的是entry.get("name")中的 Integer,所以我無法得出最終結果。

The final output of this function will be Map<String, Integer> and it will be converted into JSON response to API by the controller.

{
    "completed":2,
    "successful":8,
    "inprogress":1
}

當前代碼

List<Map<String, Integer>> result = null;
Map<String, Integer> finalresult = new HashMap<>();
map.put("id", id);
result = sqlSession.selectList("com.class.getresult",map);
System.out.println(result);
if (!result.isEmpty()) {
    for (Map<String, Integer> entry : result) {
        finalresult.put(entry.get("name"), entry.get("count"));
    }
}
return finalresult;

如何從列表中獲取名稱?

我猜您希望累積返回的結果並按狀態(已完成、成功、進行中)對它們進行分組。

然后,您應該遍歷每個List元素Map (s) 並對結果進行分組,如果已經存在,則添加狀態計數。

如果您的輸入result如下所示:

[{in progress=2, completed=1}, {completed=1, successful=2}, {in progress=3, successful=5}]
if (!result.isEmpty()) {
    for (Map<String, Integer> map : result) {
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            finalresult.compute(entry.getKey(), (k, v) -> (v == null) ? entry.getValue() : v + entry.getValue());
        }
    }
}
return finalresult;

否則,如果您的輸入result為以下形式:

[{name=completed, count=1}, {name=in progress, count=2}, {name=successful, count=3}]

然后,您需要獲取 map 各個插槽的條目:

if (!result.isEmpty()) {
    for (Map<String, String> map : result) {
        finalresult.put(map.get("name"), Integer.parseInt(map.get("count")));
    }
}
return finalresult;

或者,如果您在Java 1.8+上,則只需一行語句:

result.forEach(() -> finalresult.put(result.get("name"), Integer.parseInt(result.get("count"))));

如果您使用的是最新版本的 Mybatis,可以嘗試以下方法:

@Select("SELECT name, count FROM YOUR_TABLE")
@MapKey("name")
public Map<String,Integer> getResult( Map parameters );

希望以上對你有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM