OcelotXL OcelotXL - 1 year ago 68
Java Question

find & replace sing. char. in an ArrayList<String> element

I am interested in iterating through (re: find and replace purposes),

List<String> someList = new ArrayList<String>();

where someList is already populated in an earlier method,
and consists of, say just a couple elements, in the fashion of,
call it [a:bX, b:Xc],

where the find-and-replace String(s) of interest are, say:

String someString = "X";
String otherString = "Y";
String contentsTBD = "";

Now, ideally I thought I could've iterated over someList like so:

public void readAndReplace() {
for (int i = 0; i < someList.size(); i++) {
if (someList.get(i).contains(someString)) {
someList.get(i).replace(someString, otherString);
} else {

wherein the printout should read:

[a:bY, b:Yc]

Then, I thought this might work:

public void readAndReplace() {
for (String s : someList) {
contentsTBD += s;
for (int i = 0; i < contentsTBD.length(); i++) {
if (contentsTBD.contains(someString)) {
contentsTBD.replaceAll(someString, otherString);
} else {

but then quickly realized that this was nonsensical since
my reference to i was lost. Any advice would be really helpful.
Thank you.

Answer Source
  • First, you are not storing your Replaced String anywhere. It is gone with the wind.

  • Second, your replace will not modify the existing list. You would need to set the new string into the existing location, since you are using traditional for-loop. Or, you can have a new list, and add modified values to that list.

  • Remember, since String in Java is immutable, so all the methods of String class return a new string. They do not modify the existing one. So, you need to re-assign the returned String into a new one.

Try out this code: -

 public void readAndReplace()
      // You can also create a new list out of the existing list.
      // That way, you won't need to modify the existing one.
      List<String> newList = new ArrayList<String>();
      for(int i = 0; i < someList .size(); i++)
              newList.add(someList.get(i).replace(someString, otherString));
             //someList.set(i, someList.get(i).replace(someString, otherString));
          } else {

              // If it not contains `someString`, add it as it is to newList

       System.out.println(someList);  // Original
       System.out.println(newList);   // New List

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download