简体   繁体   中英

print range of integers in descending or ascending order in java

I have an upper bound and a lower bound and I want to return all number number between the bounds including the bounds. I know python has a range function but I'm sure if java has this method.

You can just use a for loop. Do you want to print them or return them? Your title and question disagree on this. If you want to return them, you will need to pick the type that you use to contain them.

List<Integer> ret = new ArrayList<Integer>();
for (int i = lower; i <= upper; i++) {
    ret.add(i);
}
return ret;

I will leave it as an exercise to print them, or to get them in descending order.

If you have an array if integers you can use IntRange in Apache Commons Lang:

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/IntRange.html

IntRange ir = new IntRange(int lower, int upper);
ir.toString();

More info of the various Range's you can use here:

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/class-use/Range.html

EDIT: I totally over-read the question. I saw a suggestion of an IntRange utility and I just assumed this was the classic "I want an Iterable" request, which I hear often. So ignore the below.

Simplified (without error checking):

public static List<Integer> range(final int start, final int end) {
  return new AbstractList<Integer>() {
    public int size() {
      return end - start + 1;
    }
    public Integer get(int i) {
      return start + i;
    }
  };
}

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