1

I am currently working on a project where I need to check an arraylist for a certain string and if that condition is met, replace it with the new string. I will only show the relevant code but basically what happened before is a long string is read in, split into groups of three, then those strings populate an array. I need to find and replace those values in the array, and then print them out. Here is the method that populates the arraylist:

private static ArrayList<String> splitText(String text)
{
    ArrayList<String> DNAsplit = new ArrayList<String>();
    for (int i = 0; i < text.length(); i += 3) 
    { 
        DNAsplit.add(text.substring(i, Math.min(i + 3, text.length()))); 
    }
    return DNAsplit;
}

How would I search this arraylist for multiple strings (Here's an example aminoAcids = aminoAcids.replaceAll ("TAT", "Y");) and then print the new values out. Any help is greatly appreciated.

3
  • 1
    Your splitText method is unnecessarily complicated. Just use for (int i = 0; i < text.length(); i += 3) { DNAsplit.add(text.substring(i, Math.min(i + 3, text.length()))); }. Commented Jun 5, 2016 at 22:52
  • I dont see an array anywhere in this code am i missing something or are you meaning arraylist? Commented Jun 5, 2016 at 22:52
  • @AndyTurner thank you for the revision, much cleaner. Commented Jun 5, 2016 at 23:20

3 Answers 3

6

In Java 8

list.replaceAll(s-> s.replace("TAT", "Y"));
Sign up to request clarification or add additional context in comments.

Comments

0

There is no such "replace all" method on a list. You need to apply the replacement element-wise; the only difference vs doing this on a single string is that you need to get the value out of the list, and set the new value back into the list:

ListIterator<String> it = DNAsplit.listIterator();
while (it.hasNext()) {
  // Get from the list.
  String current = it.next();

  // Apply the transformation.
  String newValue = current.replace("TAT", "Y");

  // Set back into the list.
  it.set(newValue);
}

And if you want to print the new values out:

System.out.println(DNAsplit);

Comments

0

Why dont you create a hashmap that has a key-value and use it during the load time to populate this list instead of revising it later ?

Map<String,String> dnaMap = new HashMap<String,String>() ;
dnaMap.push("X","XXX");
.
.
.
dnaMap.push("Z","ZZZ");

And use it like below :

            //Use the hash map to lookup the temp key 
    temp= text.substring(i, Math.min(i + 3, text.length())); 
            DNAsplit.add(dnaMap.get(temp));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.