Utils { public static List<String> calculateRanges(final Collection<Integer> numbers) { final List<Integer> sorted = new ArrayList<>(); sorted.addAll(numbers); Collections.sort(sorted, Comparator.naturalOrder()); final List<String> ranges = new ArrayList<>(); if (sorted.size() == 1) { ranges.add(String.valueOf(sorted.get(0))); return ranges; } final Iterator<Integer> numberIterator = numbers.iterator(); if (!numberIterator.hasNext()) { return new ArrayList<>(); } Integer first = null; Integer last = null; do { Integer number = numberIterator.next(); if (first == null) { first = number; last = number; if (!numberIterator.hasNext()) { ranges.add(String.valueOf(first)); } continue; } if (number.equals(last + 1)) { last = number; if (!numberIterator.hasNext()) { ranges.add(String.valueOf(first) + "-" + String.valueOf(last)); } continue; } else { if (first.equals(last)) { ranges.add(String.valueOf(first)); } else { ranges.add(String.valueOf(first) + "-" + String.valueOf(last)); } first = number; last = number; if (!numberIterator.hasNext()) { ranges.add(String.valueOf(first)); } continue; } } while (numberIterator.hasNext()); return ranges; }  static List<String> calculateRanges(final Collection<Integer> numbers);  }
@Test public void testCalculateRanges_simple() { final List<String> result = Utils.calculateRanges( Arrays.asList(0,1,2,3,4,5,6) ); assertEquals(1, result.size()); assertEquals("0-6", result.get(0)); }
@Test public void testCalculateRanges_one() { final List<String> result = Utils.calculateRanges( Arrays.asList(0) ); assertEquals(1, result.size()); assertEquals("0", result.get(0)); }
@Test public void testCalculateRanges_empty() { final List<String> result = Utils.calculateRanges( Arrays.asList() ); assertEquals(0, result.size()); }
@Test public void testCalculateRanges_multi() { final List<String> result = Utils.calculateRanges( Arrays.asList(0,1,3,4,6) ); assertEquals(3, result.size()); assertEquals("0-1", result.get(0)); assertEquals("3-4", result.get(1)); assertEquals("6", result.get(2)); }
@Test public void testCalculateRanges_multi2() { final List<String> result = Utils.calculateRanges( Arrays.asList(0,1,3,4,6,7) ); assertEquals(3, result.size()); assertEquals("0-1", result.get(0)); assertEquals("3-4", result.get(1)); assertEquals("6-7", result.get(2)); }
@Test public void testCalculateRanges_singles() { final List<String> result = Utils.calculateRanges( Arrays.asList(0,3,6) ); assertEquals(3, result.size()); assertEquals("0", result.get(0)); assertEquals("3", result.get(1)); assertEquals("6", result.get(2)); }