Splitting a map based on certain condition

后端 未结 1 796
无人共我
无人共我 2020-12-22 12:57

I have a map as shown below:

Key        Value
    23      20
    32      20      (20+20  =40 , min=23 max=32)
    43      18
    45      24      (24+18 =42 ,         


        
相关标签:
1条回答
  • 2020-12-22 13:35

    Instead of using a Map, you could create a Pair class that will hold the key and the value.

    class Pair {
        public int key;
        public int value;
    
        public Pair(int key, int value){
            this.key = key;
            this.value = value;
        }
    }
    

    Then create a list of pair and iterate through it. If the sum is 0, initialize the min and the max. Then for each pair iterated, add its value to the sum. If the sum is inferior continue the loop and update the max key, else you have two cases possible:

    1. The sum is equals to the limit so update the max key
    2. The sum is not equals to the limit (so it's superior), decrement the index and don't update the max key

    public static void main(String[] arg) {
        List<Integer> indexList = Arrays.asList(23,32,43,45,47,56,49,47); // get this from database
        List<Integer> valueList = Arrays.asList(20,20,18,24,10,6,2,12); // get this from database
        List<Pair> pairList = new ArrayList<>();
        for(int i = 0; i < indexList.size();i++){
            pairList.add(new Pair(indexList.get(i), valueList.get(i)));
        }
        int sum = 0;
        int min = -1;
        int max = -1;
    
        for(int i = 0; i < pairList.size(); i++){
            Pair p = pairList.get(i);
            if(sum == 0){
                min = p.key;
                max = p.key;
            }
            sum += p.value;
            if(sum < LIMIT){
                max = p.key;
            } else {
                if(sum > LIMIT){
                    i--;
                } else {
                    max = p.key;
                }
                System.out.println(min+"_"+max);
                sum = 0;
            }
        }
    }
    

    Which prints:

    23_32
    43_43
    45_56
    

    I show you how to create a list of pair through your map (use a LinkedHashMap to preserve insertion order) (obviously, you'll need to modify a little bit the Pair class):

    Map<Long, Integer> m = new LinkedHashMap<>();
    //fill your map here
    List<Pair> l = new ArrayList<>();
    for(Map.Entry<Long, Integer> entries : m.entrySet()){
        l.add(new Pair(entries.getKey(), entries.getValue()));
    }
    //Now you have a list of Pair
    
    0 讨论(0)
提交回复
热议问题