Implementing a Map where keys are sets of non-overlapping ranges

后端 未结 2 1353
广开言路
广开言路 2020-12-21 14:25

I am facing a performance issue with my current implementation using List and loops. I was thinking to make some custom Map but is it possible to o

2条回答
  •  感情败类
    2020-12-21 15:24

    UPDATE: Added full implementation

    UPDATE 2: If you want you can use RangeMap for internal theMap as suggested in the comments.

    If you key ranges don't overlap, you can create a custom container which internally stores data in TreeMap with a custom key which implements Comparable:

    class MyStorage {
        private static final class Range implements Comparable {
            private int first;
            private int last;
    
            public Range(int first_, int last_) {
                first = first_;
                last = last_;
            }
    
            // This heavily relies on that the ranges don't overlap
            @Override public int compareTo(Range other) {
                if (last < other.first)
                    return -1;
                if (first > other.last)
                    return 1;
                return 0;
            }
        }
    
        private Map theMap = new TreeMap();
    
        public void put(String key, T obj) {
            String[] ranges = key.split(";");
            for (String range : ranges) {
                //System.out.println("Adding " + range);
                String[] bounds = range.split("-");
                //System.out.println("Bounds " + bounds.length);
                int first = Integer.parseInt(bounds[0]);
                if (bounds.length == 1)
                    theMap.put(new Range(first, first), obj);
                else 
                    theMap.put(new Range(first, Integer.parseInt(bounds[1])), obj);
            }
        }
    
        public T get(String key) {
            return get(Integer.parseInt(key));
        }
    
        public T get(int key) {
            return theMap.get(new Range(key, key));
        }
    }
    
    class Main
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            MyStorage storage = new MyStorage();
            storage.put("10;20-30", 123);
            storage.put("15;31-50", 456);
    
            System.out.println(storage.get("42"));
        }
    }
    

提交回复
热议问题