How can I build a Java method that returns TRUE
if all the characters in a String
are the same using inbuilt methods - without using Regex, loops, or recursion?
Examples:
aaaaaa --> True
abaaaa --> False
Aaaaaa --> False
How can I build a Java method that returns TRUE
if all the characters in a String
are the same using inbuilt methods - without using Regex, loops, or recursion?
Examples:
aaaaaa --> True
abaaaa --> False
Aaaaaa --> False
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.
You can use String.replaceAll()
String s = "aaaaaaa";
boolean same = s.replaceAll("" + s.charAt(0), "").length() == 0;
if ( "".codePoints().distinct().count() == 1 ) { … }
char
Some of the other Answers use char
. Unfortunately the char
type is obsolete, unable to represent even half of the 143,859 characters in Unicode. Just try using the string ""
instead of "aaa"
.
Instead use code point integer numbers.
Set < Integer > codePointsDistinct = "aaaaaaa".codePoints().boxed().collect( Collectors.toSet());
boolean allSameCharacter = ( codePointsDistinct.size() == 1 ) ;
See that code run live at IdeOne.com.
true
We can make that even more brief by asking the stream to eliminate duplicates by calling .distinct()
.
boolean allSameCharacter = ( "".codePoints().distinct().count() == 1 );
You can do it without a loop at all, using recursion. It's awful, but possible:
boolean singleChar(String s) {
// Add check to make sure there is at least one char.
char first = s.charAt(0);
return singleCharRecursive(first, 1, s);
}
boolean singleCharRecursive(char first, int idx, String s) {
return idx >= s.length()
|| (s.charAt(idx) == first && singleCharRecursive (first, idx+1, s));
}
Here's another answer
I believe there maybe another option analyzing off the first character in the string to see if they all match, but this one works.
String t = "aaa";
char c = t.charAt(0);
long cnt = t.chars().filter(ch -> ch == c).count();
System.out.println(cnt==t.length());
You can use replace
method:
boolean r = "aaaaaaa".replace("a", "").length() == 0;
System.out.println(r); // true