I'm trying to convert a word such as foo
to a sum of the integer encoding of individual characters. This would be calculated as 102 + 111 + 111 equaling 324. I'm trying to achieve this using a stream from a list of characters:
String word = "foo";
Arrays
.asList(word.toCharArray())
.stream()
.mapToInt (letter -> Character.getNumericValue(letter))
.sum();
The error I'm getting is:
no suitable method found for getNumericValue(char[])
How would I go about resolving this error, or is there a better way to accomplish this?
Use the official way, and not some kind of "I want a Stream, but I can only get a Stream from a List, so I have to convert the String into a List".
String word = "foo";
word.codePoints().sum()
String.codePoints()
returns an IntStream of the code points in the stream.
Note that not every character can be represented by a single char
, emojis for example need two char
s.
int sum = word.chars().sum();
System.out.println(sum);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.