Search code examples
javacollectionsguava

What is the canonical way to transform a Range<T> into a List<T>?


There are a few options, but I am not sure which is standard.

  • Manually iterate from lower to upper bound
  • ContiguousSet
  • Something else?

Solution

  • It's not that straightforward, but of course possible. Just create ContiguousSet<T>, which is an ImmutableSortedSet, and use method asList(), eg.:

    Range<Integer> range = Range.closed(1, 5);
    ContiguousSet<Integer> ourIntegers = ContiguousSet.create(range, DiscreteDomain.integers());
    ImmutableList<Integer> ourIntegersList = ourIntegers.asList();
    System.out.println(ourIntegers); // [1‥5]
    System.out.println(ourIntegersList); // [1, 2, 3, 4, 5]
    

    Note that you may want to stick with ContiguousSet (vs using list view), because the former does not actualy store each element in memory, and the latter does, which can be an issue with big ranges.