How can I generate a list or array of sequential integers in Java?

前端 未结 8 1723
清歌不尽
清歌不尽 2020-11-28 21:54

Is there a short and sweet way to generate a List, or perhaps an Integer[] or int[], with sequential values from some

相关标签:
8条回答
  • 2020-11-28 22:50

    You can use the Interval class from Eclipse Collections.

    List<Integer> range = Interval.oneTo(10);
    range.forEach(System.out::print);  // prints 12345678910
    

    The Interval class is lazy, so doesn't store all of the values.

    LazyIterable<Integer> range = Interval.oneTo(10);
    System.out.println(range.makeString(",")); // prints 1,2,3,4,5,6,7,8,9,10
    

    Your method would be able to be implemented as follows:

    public List<Integer> makeSequence(int begin, int end) {
        return Interval.fromTo(begin, end);
    }
    

    If you would like to avoid boxing ints as Integers, but would still like a list structure as a result, then you can use IntList with IntInterval from Eclipse Collections.

    public IntList makeSequence(int begin, int end) {
        return IntInterval.fromTo(begin, end);
    }
    

    IntList has the methods sum(), min(), minIfEmpty(), max(), maxIfEmpty(), average() and median() available on the interface.

    Update for clarity: 11/27/2017

    An Interval is a List<Integer>, but it is lazy and immutable. It is extremely useful for generating test data, especially if you deal a lot with collections. If you want you can easily copy an interval to a List, Set or Bag as follows:

    Interval integers = Interval.oneTo(10);
    Set<Integer> set = integers.toSet();
    List<Integer> list = integers.toList();
    Bag<Integer> bag = integers.toBag();
    

    An IntInterval is an ImmutableIntList which extends IntList. It also has converter methods.

    IntInterval ints = IntInterval.oneTo(10);
    IntSet set = ints.toSet();
    IntList list = ints.toList();
    IntBag bag = ints.toBag();
    

    An Interval and an IntInterval do not have the same equals contract.

    Update for Eclipse Collections 9.0

    You can now create primitive collections from primitive streams. There are withAll and ofAll methods depending on your preference. If you are curious, I explain why we have both here. These methods exist for mutable and immutable Int/Long/Double Lists, Sets, Bags and Stacks.

    Assert.assertEquals(
            IntInterval.oneTo(10),
            IntLists.mutable.withAll(IntStream.rangeClosed(1, 10)));
    
    Assert.assertEquals(
            IntInterval.oneTo(10),
            IntLists.immutable.withAll(IntStream.rangeClosed(1, 10)));
    

    Note: I am a committer for Eclipse Collections

    0 讨论(0)
  • 2020-11-28 22:50

    You could use Guava Ranges

    You can get a SortedSet by using

    ImmutableSortedSet<Integer> set = Ranges.open(1, 5).asSet(DiscreteDomains.integers());
    // set contains [2, 3, 4]
    
    0 讨论(0)
提交回复
热议问题