0

I have the following:

[[Statistics (pH)], [ Upright Normal Recumbent Normal Total]]

I want to split the first element of the second element on whitespace so that I end up with:

[[Statistics (pH)], [Upright,Normal,Recumbent,Normal,Total]]

My code so far:

for (ArrayList<List<String>> row2 : StatspH) {
row2.get(1).get(0).split("\\s");
}

but nothing happens

4
  • Java strings are immutable. row2.get(1).get(0).split("\\s") splits the string, but you are discarding the returned String[]. Commented Apr 19, 2016 at 18:19
  • String methods are not mutators, in fact String itself in Java is immutable. split() will return a new instance of String[]. Commented Apr 19, 2016 at 18:19
  • 1
    Also, you'd need to trim before splitting to get that result. Commented Apr 19, 2016 at 18:21
  • Ok so how to replace the whole element with the new array from split? Commented Apr 19, 2016 at 18:27

1 Answer 1

1

Java Strings are immutable, so you need to store the return value of split("\\s") in the correct List.

I recommend something like

for (ArrayList<List<String>> row2 : StatspH) {
    List<String> stats = row2.get(1);

    // remove() returns the object that was removed
    String allStats = stats.remove(0);

    Collections.addAll(stats, allStats.split("\\s"));
}

Note that we're removing the original string first, then adding all of the 'split' values.

Sign up to request clarification or add additional context in comments.

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.