简体   繁体   中英

Java Mybatis result to Hashmap

PSQL query is returning a list of 2 values name and count.

I want to put it to a single Hashmap and return values.

the query result will be like

name        count
completed   2
successful  8
inprogress  1

I'm able to get the result in result variable. But in for loop I'm getting is Integer in entry.get("name") so I'm not able to put to finalresult.

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
}

Current Code

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;

How do I get the name of from List?

I guess you are expecting to accumulate the returned results and group them by status ( completed, successful, in progress ).

You should then iterate over each of the List element Map (s) and group the results adding the status count if already exists.

If your input result looks as follows:

[{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;

Else if your input result is of the below form:

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

You would then need to get the map the entries to respective slots:

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

Or a just a single line statement if you are on Java 1.8+ :

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

If you are using the recent version of Mybatis, you can try the following:

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

Hope the above helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM