char
obsolete
The char
primitive type, and its wrapper class Character
, have been legacy since Java 2. As a 16-bit value, these types are physically incapable of representing most characters.
Avoid char
/Character
types.
Code points
Instead, use Unicode code point integer numbers to work with individual characters.
Your code is mixing char
values with code point code. Do not mix the types. Avoid char
, use only code points.
Unfortunately, Java lacks a type for code points. So we use the int
/Integer
with several methods awkwardly spread out across various classes including String
, StringBuilder
, and Character
.
Map< Integer , Integer > transMap =
Map.of(
"G".codePointAt(0) , "C".codePointAt(0) ,
"C".codePointAt(0) , "G".codePointAt(0) ,
"T".codePointAt(0) , "A".codePointAt(0) ,
"A".codePointAt(0) , "U".codePointAt(0)
)
;
The transcription method swaps integers. Then collect these integers using StringBuilder#appendCodePoints
.
By the way, your transcribe
method could be made more general by taking an parameter of type CharSequence
rather than String
. CharSequence
is an interface implemented by String
. The only method we need to call on the argument is codePoints
. That method is required by CharSequence
.
String transcribe( final CharSequence dnaStrand ) {
return
dnaStrand
.codePoints()
.map( codePoint -> transMap.get( codePoint ) )
.collect(
StringBuilder :: new,
StringBuilder :: appendCodePoint,
StringBuilder :: append
)
.toString() ;
}