I've got:
String s = "ZpglnRxqenU"
I need to assign a number to each character in the string like:
z-1
p-2
g-3
l-4
n-5
r-6
x-7
q-8
e-9
n-10
u-11
I do not want to count the frequency of characters.
I tried to use HashMap
:
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i ) {
map.put(String.valueOf(s.charAt(i)), i 1);
}
But Map
a has unique key and I lost first n occurrence
How do I count letters?
CodePudding user response:
Swap the key-value of your map. Use the number for the key, as it will be unique.
Use a NavigableMap
to keep them in order.
NavigableMap< Integer , String > = new TreeMap<>() ;
Example code using conventional style.
String input = "ZpglnRxqenU";
int[] codePoints = input.codePoints().toArray();
NavigableMap < Integer, String > numberedCharacters = new TreeMap <>();
for ( int i = 1 ; i <= codePoints.length ; i )
{
Integer index = Integer.valueOf( i );
numberedCharacters.putIfAbsent( index , Character.toString( codePoints[ index - 1 ] ) );
}
Example code using streams & lambdas. Same effect, not necessarily better in this particular case.
String input = "ZpglnRxqenU";
int[] codePoints = input.codePoints().toArray();
NavigableMap < Integer, String > numberedCharacters =
IntStream
.rangeClosed( 1 , codePoints.length )
.mapToObj( Integer :: valueOf )
.collect(
Collectors.toMap(
Function.identity() ,
index -> Character.toString( codePoints[ index - 1 ] ) ,
( o1 , o2 ) -> o1 ,
TreeMap :: new )
);
To get all the characters from the map, call values
. The resulting Collection
object promises to iterate in the order of iteration of the map’s keys.
String recreated = String.join( "" , numberedCharacters.values() );
Dump to console.
System.out.println( "input = " input );
System.out.println( "numberedCharacters = " numberedCharacters );
System.out.println( "recreated = " recreated );
When run.
input = ZpglnRxqenU
numberedCharacters = {1=Z, 2=p, 3=g, 4=l, 5=n, 6=R, 7=x, 8=q, 9=e, 10=n, 11=U}
recreated = ZpglnRxqenU
CodePudding user response:
If you want to count the number of characters in a string use s.length();
.
If you want to count the number of different characters in a String, you already can with the code you wrote. map.size()
will give exactly that, because the map only stores each key once (in your case the 'letters' (they are called char's in java, chars is a diminutive for characters)).
How put()
in maps work:
The first time you put a key to the map, it is added with the value you give, the second time the value is changed.