[Java] IntStream.range, rangeClosed

epiphanyยท2022๋…„ 12์›” 29์ผ
1

Programmers School

๋ชฉ๋ก ๋ณด๊ธฐ
22/22
post-thumbnail

๐Ÿ›ซ Programmers School์—์„œ ์ง์‚ฌ๊ฐํ˜• ๋ณ„์ฐ๊ธฐ ๋ฌธ์ œ ํ’€์ด๋ฅผ ๋ณด๋ฉฐ ์ข‹์€ ๊ฐœ๋…์„ ์•Œ๊ฒŒ ๋˜์–ด ์ •๋ฆฌ

๐Ÿ“‘ Code

  • ๋‚ด ์ฝ”๋“œ
for (int i=0; i<b; i++){
    for (int j=0; j<a; j++){
        System.out.print("*");
    }
    System.out.println("");
}
  • ๋‹ค๋ฅธ ์‚ฌ๋žŒ ์ฝ”๋“œ
IntStream.range(0, a).forEach(s -> sb.append("*"));
IntStream.range(0, b).forEach(s -> System.out.println(sb.toString()));

๐Ÿงฉ IntStream.range

IntStream.range๋Š” ๋ฐ์ดํ„ฐ ํƒ€์ž…์ด Integer์ธ ๊ฒƒ์„ ๋ฒ”์œ„์— ๋งž๊ฒŒ ์ฐจ๋ก€๋Œ€๋กœ ์ถœ๋ ฅํ•ด์ฃผ๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค.
IntStream.range(1,11)๋กœ ์‚ฌ์šฉํ•˜๊ฒŒ ๋œ๋‹ค๋ฉด 1~10๊นŒ์ง€ ์ˆซ์ž๋ฅผ ์ถœ๋ ฅํ•ด์ค€๋‹ค.

import java.util.stream.IntStream;

public class test{
    public static void main(String[] args){
        IntStream.range(1,11).forEach(i->{
            System.out.println(i);
        });
    }
}

// output:
1
2
3
4
5
6
7
8
9
10

๐Ÿงฉ rangeClosed

rangeClosed๋ฅผ 2๋ฒˆ์งธ ๋ฒ”์œ„๊นŒ์ง€ ํฌํ•จํ•ด์ฃผ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค.

๊ฑฐ์˜ ๋Œ€๋ถ€๋ถ„์˜ ์–ธ์–ด๋Š” range๋ฅผ ์‚ฌ์šฉํ• ๋•Œ (a, b)๋ฅผ ๋ฒ”์œ„๋กœ ํ•œ๋‹ค๋ฉด a~b-1๊นŒ์ง€ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.
๊ทธ๋ž˜์„œ ์œ„์— IntStream์—์„œ ์‚ฌ์šฉ๋œ range(1,11)์€ 1~10๊นŒ์ง€๋ฅผ ์˜๋ฏธํ•œ๋‹ค.

rangeClosed๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด rangeClosed(1,10)์ด range(1,11)๊ฐ€ ๋™์ผํ•œ ๋™์ž‘์„ ํ•˜๊ฒŒ ๋œ๋‹ค.

import java.util.stream.IntStream;

public class test{
    public static void main(String[] args){
        IntStream.rangeClosed(1,5).forEach(i->{
            System.out.println(i);
        });
    }
}
// output:
1
2
3
4
5

๐Ÿ“š Reference

0๊ฐœ์˜ ๋Œ“๊ธ€