Check If All Characters in String Are Same Without Loops in Java

How can I build a Java method that returns TRUE if all the characters in the a String is the same without using Regex, loops, or recursion?

Examples: 
aaaaaa --> True
abaaaa --> False
Aaaaaa --> False

Answer

You can convert the string to an IntStream using .chars() and check if the stream has distinct count of 1 using .distinct().count() == 1.

String s = "aaaaaa";
boolean isAllCharsSame = s.chars().distinct().count() == 1;

isAllCharsSame will be true if all characters in the string s are same, otherwise false.

Edit:

String s = "aaaaaa";
boolean isAllCharsSame = s.codePoints().distinct().count() == 1;

.chars() won’t work for Unicode codepoints like "๐Ÿ‘‹๐Ÿ‘‹๐Ÿ‘‹", use .codePoints() for that. Thanks to @BasilBourque for pointing this out.

Leave a Reply

Your email address will not be published. Required fields are marked *