I have to count the characters in a given String. I save the counts to a map Map<Character, Long>
. The code does not work with some special symbols like "two hearts". When I convert such a special symbol into a character, then I get the compiler error "Too many characters in character literal" or similar. Why does this happen and how to fix it ?
Here is some rough code to demonstrate the problem. This is not the full code.
import java.util.HashMap;
import java.util.Map;
public class Demo {
public static void main(String[]args){
String twoHeartsStr = "";
Map<Character, Long> output = new HashMap<>();
output.put(twoHeartsStr.charAt(0), 1L);
//Compiler error:
//intellij IDE compiler : Too many characters in character literal.
//java: unclosed character literal.
Map<Character, Long> expectedOutput = Map.of('', 1L);
System.out.println("Maps are equal : " + output.equals(expectedOutput));
}
}
EDIT : Updated solution after getting answers to this question.
import java.util.HashMap;
import java.util.Map;
public class Demo {
public static void main(String[]args){
String twoHeartsStr = "";//Try #, alphabet, number etc.
Map<String, Long> output = new HashMap<>();
int codePoint = twoHeartsStr.codePointAt(0);
String charValue = String.valueOf(Character.toChars(codePoint));//Size = 2 for twoHearts.
output.put(charValue, 1L);
Map<String, Long> expectedOutput = Map.of("", 1L);
System.out.println("Maps are equal : " + output.equals(expectedOutput));//true.
}
}