I was wondering how i can get these values and put it together in a new String
class Rna {
static Map<Character, Character> map = (Map<Character, Character>) Map.of(
'G', 'C',
'C', 'G',
'T', 'A',
'A', 'U'
);
String transcribe(String dnaStrand) {
return dnaStrand.chars()
.map(c -> map.get(c))
.collect(StringBuilder::new, StringBuilder::appendCodePoint ,StringBuilder::append)
.toString();
}
}
transcribe should return an String like "AUGC". Now i`m getting this exception.

CodePudding user response:
I think the problem is that you use the String.chars() method which returns a stream of ints but you cannot expect autoboxing of an int to a Character.
The map doesn't contain int or Integer keys, so always will return null for the get.
As a solution you could try to cast c to a char or even create a Character instance manually:
.map(c -> map.get((char)c)) or .map(c -> map.get(Character.valueof((char)c))
CodePudding user response:
If you want to obtain map value, you can not have a String like "AUGC", may be "UAGC"?
And you can read more about Collection, Map and LinkedHashMap.
If you will try this code, all will be work.
public class Main {
public static void main(String[] args) {
Map<Character, Character> map = new LinkedHashMap();
map.put('G', 'C');
map.put( 'C', 'G');
map.put( 'T', 'A');
map.put( 'A', 'U');
Test test = new Test();
System.out.println(test.transcribe(map));
}
}
public class Test {
String transcribe(Map<Character, Character> map) {
StringBuilder stringBuilder = new StringBuilder();
for (Character ch : map.values()) {
stringBuilder.append(ch);
}
return String.valueOf(stringBuilder.reverse());
}
}
CodePudding user response:
Here is one way to do it. The method is called with a string of keys from your base/pair map. Any characters in that string map to null are filtered out. This presumes a map instance visible to the method. Otherwise it will need to be provided as an argument.
chars()provides a stream of characters- get the mapping for current character and convert to String
- filter out any null values.
- join String characters into long strand and return.
static String transcribe(String dnaStrand) {
return dnaStrand.chars()
.mapToObj(c -> String.valueOf(map.get((char)c)))
.filter(str->!str.equals("null"))
.collect(Collectors.joining());
}
System.out.println(transcribe("GCTA"));
will return and print
CGAU
