-5

Given max number and range number, I want print out the following, but as short as possible. I don't know if this accomplish using IntStream.

input: max = 36 (or any number) range = 10 (or any number)

output: 0-9 10-19 20-29 30-35

my code:

totalItems=35
rangeMax=10
rangeFrom=0
rangeTo=0
while (true) {
    if(totalItems>rangeTo+rangeMax){
        rangeFrom=rangeTo+1;
        rangeTo=rangeTo+rangeMax;
    } else if(totalItems>rangeTo+1){
        rangeFrom=rangeTo+1;
        rangeTo=rangeTo+(totalItems-rangeFrom);
    } else {
        return null;
    }
}
cunglabuon
  • 11
  • 6

1 Answers1

0
public static void loopingIssue(Integer totalItems, Integer range) {
    IntStream.range(0, totalItems).filter(i -> i % range == 0)
            .mapToObj(e -> mapToGroup(e, totalItems, range))
            .forEach(System.out::print);
}

public static String mapToGroup(Integer e, Integer totalItems, Integer maxRange) {
    if (e + maxRange >= totalItems) {
        return e + "-" + (totalItems - 1);
    } else {
        return e + "-" + (e + maxRange - 1) + ", ";
    }

}
Rahul B
  • 132
  • 1
  • 1
  • 11