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 ordinal = 1 ; ordinal <= codePoints.length ; ordinal++ )
{
numberedCharacters.putIfAbsent(
ordinal ,
Character.toString( codePoints[ ordinal - 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 )
.boxed()
.collect(
Collectors.toMap(
Function.identity() ,
ordinal -> Character.toString( codePoints[ ordinal - 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