How to implement a Group function in Java
This article shows you how to achieve a Group function in Java, the content is concise and easy to understand, it can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
The API method is as follows:
/ * keyColumn: new String [] {"xxxName", "xxxType"}
* condition: query condition, which can be empty
* initial: group statistics of initial variables, and automatically provide initial variables for each column for empty time.
* reduce: record processing function
* finalize: finalize function, which can be empty
* / public BasicDBList group (String [] keyColumn, DBObject condition, DBObject initial, String reduce, String finalize) {DBCollection coll = getCollection (); DBObject key = new BasicDBObject (); for (int I = 0; I < keyColumn.length; iTunes +) {key.put (keyColumn [I], true);} condition = (condition = null)? New BasicDBObject (): condition; if (StringUtils.isEmpty (finalize)) {finalize = null;} if (initial = = null) {/ / define some initial variables initial = new BasicDBObject (); for (int I = 0; I < keyColumn.length; iTunes +) {DBObject index = new BasicDBObject () Index.put ("count", 0); index.put ("sum", 0); index.put ("max", 0); index.put ("min", 0); index.put ("avg", 0); index.put ("self", "") Initial.put (keyColumn [I], index);} BasicDBList resultList = (BasicDBList) coll.group (key, condition, initial, reduce, finalize); return resultList;}
Implementation case:
/ / Task Statistics @ Action (value = "getTaskStatistic", results = {@ Result (name = "success", type = "json", params = {"includeProperties", "jsonResult"}) public String getTaskStatistic () {DBObject initial = new BasicDBObject (); DBObject index = new BasicDBObject (); index.put ("count", 0); index.put ("taskStatus", "") Initial.put ("taskStatus", index); String reduce = "function (doc, out) {" + "out.taskStatus.count = out.taskStatus.count+=1;" + "out.taskStatus.inspectStatus = doc.taskStatus;" + "}" BasicDBList group = (BasicDBList) taskStatusService.group (new String [] {"taskStatus"}, null, initial, reduce, null); this.jsonResult = group.toString (); return SUCCESS;}
Return data:
[{"taskStatus": {"count": 4.0," taskStatus ":" Finished "}, {" taskStatus ": {" count ": 3.0," taskStatus": "Received"}, {"taskStatus": {"count": 2.0, "taskStatus": "UnReceive"}}] the above is how to implement a Group function in Java. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.