2

I'm having some problems with replacing String field's content in a List member.

I have a List of objects and one of the fields inside that list is String. So as an example I have the following with getters and setters.

public class MyObject {
  private String message;
  private int numbers;
...

Let's assume I've created a list of MyObject and there are 3 of them in that list and I've added values to them from somewhere external like a database.

List<MyObject> myObject = new ArrayList<>();

The problem lies in that String message. Let's say the String field in the first 3 entries equals as the following.

"First message"
"Second message"
"Third message"

How can I iterate through the List of myObject's String message field and replace the alphabetical content "First" with new content such as "1st" and so on and so forth.

3
  • Create an array of strings of 1st, 2nd, 3rd.. and in parallel iterate through them while exchanging strings Commented Jul 21, 2016 at 14:59
  • 1
    Would you post an minimal reproducible example ? Commented Jul 21, 2016 at 15:00
  • Do you have a collection of the substitution you want to make? Are you planning on replacing all ordinals? Commented Jul 21, 2016 at 15:01

3 Answers 3

1

You could only do that if your class MyObject allows you to update its internal string; for example by providing a setter method.

In other words:

  1. you iterate your list of MyObject objects
  2. for each of that objects, you have to query its message
  3. then you would have to call a setter to update its content
Sign up to request clarification or add additional context in comments.

Comments

1

You can use an Iterator. But your list has to be String type.

Example

ArrayList<String> myObject = new ArrayList<>();
ListIterator litr = myObject.listIterator();
  while(litr.hasNext()) {
     String element = litr.next();
     if(element.equalsTo("first message"))
        element = "1st message";
       litr.set(element);
  }

Hope this help.

Comments

0

You should create an array that would look as it follows:

String[] s = new String[10];
s[0] = "th";
s[1] = "st";
s[2] = "nd";
s[3] = "rd";
s[4] = "th";
s[5] = "th";
s[6] = "th";
s[7] = "th";
s[8] = "th";
s[9] = "th";

Now it's enough to loop through your list and replace first word in String field message with current index i appended with s[i%10].

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.