maps集合里面的结果需要除以总数,然后使用DecimalFormat弄成百分比,
所以是要显示两位小数嘛?
示例代码如下:
public class App {
public static void main(String[] args) {
String resultStr = " \n" +
"{\n" +
" \"code\": 200,\n" +
" \"data\":{\n" +
" \"records\":[\n" +
" {\n" +
" \"id\":917834041955188736,\n" +
" \"alertTime\":\"2021-12-07 17:44:48\",\n" +
" \"messageType\":3,\n" +
" \"snapId\":101124,\n" +
" \"rank\":\"1\",\n" +
" \"alertText\":\"低电压穿越保护\",\n" +
" },\n" +
" {\n" +
" \"id\":917834020232888320,\n" +
" \"alertTime\":\"2021-12-07 17:44:42\",\n" +
" \"messageType\":1,\n" +
" \"snapId\":101124,\n" +
" \"rank\":\"3\",\n" +
" \"alertText\":\"低电压穿越保护\",\n" +
" },\n" +
" {\n" +
" \"id\":917833742737735680,\n" +
" \"alertTime\":\"2021-12-07 17:43:36\",\n" +
" \"messageType\":3,\n" +
" \"snapId\":101124,\n" +
" \"rank\":\"2\",\n" +
" \"alertText\":\"低电压穿越保护\",\n" +
" },\n" +
" {\n" +
" \"id\":917833717546745856,\n" +
" \"alertTime\":\"2021-12-07 17:43:30\",\n" +
" \"messageType\":1,\n" +
" \"snapId\":101124,\n" +
" \"rank\":\"3\",\n" +
" \"alertText\":\"低电压穿越保护\",\n" +
" }\n" +
" ],\n" +
" \"size\": 20,\n" +
" }\n" +
" }";
JSONObject result = JSONObject.parseObject(resultStr);
JSONArray records = result.getJSONObject("data").getJSONArray("records");
Integer size = result.getJSONObject("data").getInteger("size");
// 结果
Map<String, Double> data = records.toJavaList(JSONObject.class)
.stream().collect(Collectors.groupingBy(item -> "rank" + item.getInteger("rank"), Collectors.counting()))
.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue() * 1.0 / size));
// {"rank1":0.05,"rank2":0.05,"rank3":0.1}
System.out.println(JSONObject.toJSONString(data));
}
}
如有帮助,请采纳。
把这几行改一下
int sum = a + b + c + d + e;
Map<String, Float> maps = new LinkedHashMap<>();
maps.put("rank1", getValue(a, sum));
maps.put("rank2", getValue(b, sum));
maps.put("rank3", getValue(c, sum));
maps.put("rank4", getValue(d, sum));
maps.put("rank5", getValue(e, sum));
float getValue(int n, int sum) {
return (float) Math.round((float) n * 100 / sum) / 100;
}