Numbers { public static Set<Range<Integer>> toRanges(Iterable<Integer> values) { ImmutableSet.Builder<Range<Integer>> builder = ImmutableSet.builder(); PeekingIterator<Integer> iterator = Iterators.peekingIterator(Sets.newTreeSet(values).iterator()); while (iterator.hasNext()) { int start = iterator.next(); int end = start; while (iterator.hasNext() && iterator.peek() == end + 1) { end++; iterator.next(); } builder.add(Range.closed(start, end)); } return builder.build(); } private  Numbers(); static Set<Range<Integer>> toRanges(Iterable<Integer> values); static Range<Integer> toRange(IRange range); static Set<Integer> rangesToInstanceIds(Iterable<IRange> ranges); static Set<IRange> convertRanges(Set<Range<Integer>> ranges);  }
@Test public void testToRanges() { assertEquals(ImmutableSet.<Range<Integer>>of(), Numbers.toRanges(ImmutableList.<Integer>of())); assertEquals(ImmutableSet.of(Range.closed(1, 1)), Numbers.toRanges(ImmutableList.of(1))); assertEquals(ImmutableSet.of(Range.closed(0, 3)), Numbers.toRanges(ImmutableList.of(0, 1, 2, 3))); assertEquals(ImmutableSet.of(Range.closed(0, 3), Range.closed(5, 5)), Numbers.toRanges(ImmutableList.of(0, 1, 2, 3, 5))); assertEquals( ImmutableSet.of( Range.closed(0, 1), Range.closed(5, 6), Range.closed(9, 9), Range.closed(100, 100)), Numbers.toRanges(ImmutableList.of(0, 1, 5, 6, 9, 100))); }