I am trying to convert characters in a string into a new character. Essentially it would convert ATCG into TAGC. Is there a shorter way of doing this than writing a for loop and checking each character such as the tr command in bash?
Asked
Active
Viewed 80 times
-3
-
1Give a minimal verifiable example of what you're doing so we can help you. Read this https://stackoverflow.com/help/asking – Victor M Perez Jan 09 '18 at 16:17
-
Depends, can you define the pattern **regularly**? – Elliott Frisch Jan 09 '18 at 16:18
-
1You'd have to have a `Map` declaring keys and values. Then loop or stream the characters, do the conversion, and collect to String. For people unclear what `tr` is, see: https://en.wikipedia.org/wiki/Tr_(Unix) – ifly6 Jan 09 '18 at 16:18
-
@ElliottFrisch seems like base paring in DNA. In short: yes. Substitute all `'A'`'s with `'T'`'s (and vice-versa) and all `'C'`'s with `'G'`'s (and vice-versa). [idownvotedbecau.se/noresearch/](http://idownvotedbecau.se/noresearch/) – Turing85 Jan 09 '18 at 16:20
-
@Turing85 I considered that, it could also be swap each adjacent pair of characters (in this example). – Elliott Frisch Jan 09 '18 at 17:16
1 Answers
0
@ifly6's comment already sketched the way to go:
A Map
defines the conversion rules for single characters.
The String
transformation is done by streaming the characters,
doing the conversion for each character (using the Map
),
and collecting them to a String
.
public class Main {
private static Map<Character, Character> charMap = new HashMap<>();
static {
charMap.put('A', 'T');
charMap.put('T', 'A');
charMap.put('C', 'G');
charMap.put('G', 'C');
}
public static String transform(String s) {
return s.chars() // IntStream
.mapToObj(c -> charMap.get((char) c)) // Stream<Character>
.map(Object::toString) // Stream<String>
.collect(Collectors.joining()); // String
}
public static void main(String[] args) {
System.out.println(transform("ATTCGAGC")); // prints "TAAGCTCG"
}
}
You will notice that (at least for newbies) streams are much harder
to understand than conventional for
loops.
I recommend to read about Java 8 streams and the Javadocs of the methods used in the code above.

Thomas Fritsch
- 9,639
- 33
- 37
- 49