๋ฌธ์žฅ ๋‚ด์—์„œ ์‚ฌ์šฉ๋œ distinct ๋ฌธ์ž ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ

ํ•œ ๋ฌธ์žฅ ์•ˆ์—์„œ ์‚ฌ์šฉ๋œ distinct ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•ด์•ผ ํ•œ๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”?

stream์ด ๋‚˜์˜ค๊ธฐ ์ „์ด์—ˆ๋‹ค๋ฉด ๊ทธ์ € String์„ ์บ๋ฆญํ„ฐ ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค์–ด์„œ loop๋ฅผ ๋Œ๋ ค set์— ๋„ฃ์€ ๋’ค set์˜ ์‚ฌ์ด์ฆˆ๋ฅผ ๊ตฌํ•˜๋ฉด ๋๊ฒ ์ฃ .

์•„๋ž˜์ฒ˜๋Ÿผ ๋ง์ด์ฃ .

    String sentence = "Computer users take it for granted that their systems can do more than one thing at a time.";
    
    Set<Character> s = new HashSet<>();
    for (char c : sentence.toCharArray()) {
    	s.add(c);
    }
    
    System.out.println(s.size());

ํ•˜์ง€๋งŒ stream ์„ ์ด์šฉํ•˜๋ฉด ํ•œ์ค„๋กœ ํ•ด๊ฒฐ์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

 

Stream์„ ์ด์šฉํ•œ distinct ๋ฌธ์ž ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ

stream์—๋Š” distinct() ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ์œผ๋ฉฐ ์ด๋Š” ํ•ด๋‹น ์ŠคํŠธ๋ฆผ๋‚ด์—์„œ distinctํ•œ ๊ฒƒ๋“ค๋งŒ ์ถ”์ถœํ•ด์ค๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  count()๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ทธ ๊ฐœ์ˆ˜๋ฅผ ์…€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๊ทธ๋ž˜์„œ ์œ„์—์„œ set๊ณผ for-loop๋ฅผ ์‚ฌ์šฉํ•œ ๋ถ€๋ถ„์„ stream์„ ์ด์šฉํ•˜์—ฌ ํ•œ์ค„๋กœ ์ค„์ด๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

    String sentence = "Computer users take it for granted that their systems can do more than one thing at a time.";

    long distinctCharsCount = sentence.chars().distinct().count();

    System.out.println(distinctCharsCount);

ํ›จ์”ฌ ๊ฐ„๋‹จํ•˜๊ฒŒ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.