结果集处理:区间分组数量相加

package com.hz.demo;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.MapUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo4 {
    public static void main(String[] args) {

        List<Map<String,Object>> newData = Lists.newArrayList();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("vin", "AAA");
        map1.put("consumption", 55.2);

        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("vin", "BBB");
        map2.put("consumption", 23.2);

        Map<String, Object> map6 = new HashMap<String, Object>();
        map6.put("vin", "BBB");
        map6.put("consumption", 101.2);

        Map<String, Object> map7 = new HashMap<String, Object>();
        map7.put("vin", "BBB");
        map7.put("consumption", 103.2);

        Map<String, Object> map8 = new HashMap<String, Object>();
        map8.put("vin", "CCC");
        map8.put("consumption", 300.0);

        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put("vin", "DDD");
        map4.put("consumption", 3.2);

        Map<String, Object> map5 = new HashMap<String, Object>();
        map5.put("vin", "DDD");
        map5.put("consumption", 4.2);

        newData.add(map1);
        newData.add(map2);
        newData.add(map6);
        newData.add(map7);
        newData.add(map8);
        newData.add(map4);
        newData.add(map5);

        Map<String,Integer> rs = Maps.newLinkedHashMap();
        Map<String, Object> maxData = newData.stream().max((Map<String, Object> d1, Map<String, Object> d2) -> MapUtils.getDouble(d1, "consumption")
                .compareTo(MapUtils.getDouble(d2, "consumption"))).get();
        int maxC  = (int)Math.ceil(MapUtils.getDouble(maxData, "consumption") / 10);
        for(int j = 0; j < 10; j++){
            int min = maxC * j ;
            int max = (j+1) * maxC;
            int count = 0;
            rs.put(min +"-" + max,count);
        for (int i = 0; i < newData.size(); i++) {
            Map<String,Object> map = newData.get(i);
            Double consumption  = MapUtils.getDouble(map, "consumption");
                if(consumption > min && consumption <= max){
                    count++;
                    rs.put(min +"-" + max,count);
                }
            }
        }
        System.out.println(JSON.toJSONString(rs));
    }
}

  

posted @ 2020-03-17 14:37  蔡徐坤1987  阅读(207)  评论(0编辑  收藏  举报