void () { List<MyRange> markers = getAllMarkers(); SortedMap<Integer, Integer> allValues = new TreeMap<>(); for (MyRange marker : markers) { int offset = marker.getStartOffset(); Integer sumForOffset = allValues.get(offset); int value = marker.myValue; allValues.put(offset, sumForOffset == null ? value : sumForOffset + value); } int runningSum = 0; int prevOffset = Integer.MIN_VALUE; for (Map.Entry<Integer, Integer> e : allValues.entrySet()) { int offset = e.getKey(); if (prevOffset < (offset - 1)) checkSumForOffset(offset - 1, runningSum); runningSum += e.getValue(); checkSumForOffset(offset, runningSum); prevOffset = offset; } checkSumForOffset(prevOffset + 1, runningSum); }