Merge Intervals (Java) - Easy to Understand - Not the most performant
\nclass CountIntervals {\n    \n    TreeMap<Integer, Integer> tree;\n    int count;\n\n    public CountIntervals() {\n        this.tree = new TreeMap<>();\n    
```\nclass CountIntervals {\n    \n    TreeMap<Integer, Integer> tree;\n    int count;\n\n    public CountIntervals() {\n        this.tree = new TreeMap<>();\n        this.count = 0;\n    }\n    \n    public void add(int left, int right) {\n\t    // Keep removing lower entries as long as they extend current interval\n        while (this.tree.floorKey(left) != null) {\n            int fk = this.tree.floorKey(left);\n\t\t\t// The lower range is totally out of the current range\n            if (this.tree.get(fk) < left) {\n                break;\n            }\n            left = Math.min(left, fk);\n            right = Math.max(right, this.tree.get(fk));\n\t\t\t// remove the previously counted values\n            this.count -= (this.tree.get(fk) - fk + 1);\n            this.tree.remove(fk);\n        }\n\t\t// Keep removing higher entries as long as they extend current interval\n        while (this.tree.floorKey(right) != null) {\n            int fk = this.tree.floorKey(right);\n\t\t\t// the range is totally out of the current range\n            if (this.tree.get(fk) < left) {\n                break;\n            }\n            left = Math.min(left, fk);\n            right = Math.max(right, this.tree.get(fk));\n\t\t\t// remove the previously counted values\n            this.count -= (this.tree.get(fk) - fk + 1);\n            this.tree.remove(fk);\n        }\n        this.count += (right - left + 1);\n        this.tree.put(left, right);\n    }\n    \n    public int count() {\n        return this.count;\n    }\n}\n```
['Java']