DISTINCT (1)

문장 내에서 사용된 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);

훨씬 간단하게 구할 수 있습니다.