简体   繁体   中英

Replace strings populated in an ArrayList<String> with other values

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.

在Java 8中

list.replaceAll(s-> s.replace("TAT", "Y"));

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);

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM