title: How to count grapheme clusters or "perceived" emoji characters in Java
body: <p>I'm looking to count the number of perceived emoji characters in a provided Java string. I'm currently using the <a href="https://github.com/kcthota/emoji4j" rel="noreferrer">emoji4j</a> library, but it doesn't work for grapheme clusters like this one: ‍‍‍</p>
  
  <p>Calling <code>EmojiUtil.getLength("‍‍‍")</code> returns <code>4</code> instead of <code>1</code>, and similarly calling <code>EmojiUtil.getLength("‍‍‍")</code> returns <code>5</code> instead of <code>2</code>.</p>
  
  <p>Are there any APIs or methods on <code>String</code> in Java that make it easy to count grapheme clusters?</p>
  
  <p>I've been hunting around but understandably the <code>codePoints()</code> method on a <code>String</code> includes not only the visible emojis, but also the zero width joiners.</p>
  
  <p>I also attempted this using the <code>BreakIterator</code>:</p>
  
  <pre><code>public static int getLength(String emoji) {
      BreakIterator it = BreakIterator.getCharacterInstance();
      it.setText(emoji);
      int emojiCount = 0;
      while (it.next() != BreakIterator.DONE) {
          emojiCount++;
      }
      return emojiCount;
  }
  </code></pre>
  
  <p>But it seems to behave identically to the <code>codePoints()</code> method, returning <code>8</code> for something like <code>"‍‍‍"</code>.</p>