简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM