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

前端 未结 8 1722
清歌不尽
清歌不尽 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:24

    This is the shortest I could get using Core Java.

    List<Integer> makeSequence(int begin, int end) {
      List<Integer> ret = new ArrayList(end - begin + 1);
    
      for(int i = begin; i <= end; i++, ret.add(i));
    
      return ret;  
    }
    
    0 讨论(0)
  • 2020-11-28 22:35

    This one might works for you....

    void List<Integer> makeSequence(int begin, int end) {
    
      AtomicInteger ai=new AtomicInteger(begin);
      List<Integer> ret = new ArrayList(end-begin+1);
    
      while ( end-->begin) {
    
        ret.add(ai.getAndIncrement());
    
      }
      return ret;  
    }
    
    0 讨论(0)
  • 2020-11-28 22:44

    With Java 8 it is so simple so it doesn't even need separate method anymore:

    List<Integer> range = IntStream.rangeClosed(start, end)
        .boxed().collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-28 22:47

    This is the shortest I could find.

    List version

    public List<Integer> makeSequence(int begin, int end)
    {
        List<Integer> ret = new ArrayList<Integer>(++end - begin);
    
        for (; begin < end; )
            ret.add(begin++);
    
        return ret;
    }
    

    Array Version

    public int[] makeSequence(int begin, int end)
    {
        if(end < begin)
            return null;
    
        int[] ret = new int[++end - begin];
        for (int i=0; begin < end; )
            ret[i++] = begin++;
        return ret;
    }
    
    0 讨论(0)
  • 2020-11-28 22:48

    Well, this one liner might qualify (uses Guava Ranges)

    ContiguousSet<Integer> integerList = ContiguousSet.create(Range.closedOpen(0, 10), DiscreteDomain.integers());
    System.out.println(integerList);
    

    This doesn't create a List<Integer>, but ContiguousSet offers much the same functionality, in particular implementing Iterable<Integer> which allows foreach implementation in the same way as List<Integer>.

    In older versions (somewhere before Guava 14) you could use this:

    ImmutableList<Integer> integerList = Ranges.closedOpen(0, 10).asSet(DiscreteDomains.integers()).asList();
    System.out.println(integerList);
    

    Both produce:

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    0 讨论(0)
  • 2020-11-28 22:49

    The following one-liner Java 8 version will generate [ 1, 2 ,3 ... 10 ]. The first arg of iterate is the first nr in the sequence, and the first arg of limit is the last number.

    List<Integer> numbers = Stream.iterate(1, n -> n + 1)
                                  .limit(10)
                                  .collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题