Avoid printing the last comma

前端 未结 13 591
无人及你
无人及你 2020-12-03 14:58

I\'m trying to print this loop without the last comma. I\'ve been Googling about this and from what i\'ve seen everything seems overcomplex for such a small problem. Surely

13条回答
  •  情书的邮戳
    2020-12-03 15:37

    Java 8:

    IntStream.rangeClosed(a, b)
             .collect(Collectors.joining(","));
    

    If you want to perform interleaving actions:

    Java 8:

    IntStream.rangeClosed(a, b)
             .peek(System.out::print)
             .limit(b - a) // [a:(b-1)]
             .forEach(i -> System.out.print(","));
    

    Java 9:

    IntStream.rangeClosed(a, b)
             .peek(System.out::print)
             .takeWhile(i -> i < b) // [a:(b-1)]
             .forEach(i -> System.out.print(","));
    

提交回复
热议问题