简体   繁体   English

替换在ArrayList中填充的字符串 <String> 与其他值

[英]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. 我目前在一个项目中,需要检查某个特定字符串的arraylist,如果满足该条件,请用新字符串替换它。 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: 这是填充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. 我将如何在该aminoAcids = aminoAcids.replaceAll ("TAT", "Y");搜索多个字符串(下面是一个示例aminoAcids = aminoAcids.replaceAll ("TAT", "Y"); ),然后打印出新值。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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