• Post Reply Bookmark Topic Watch Topic
  • New Topic

Join String elements in ArrayList  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to join String elements from one index to another in an ArrayList. Here is what i could only come up with:


Is there a way i can join for every 7 elements in the loop into one String and add it to a new array list as a new element.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Please explain what you mean. Do you want to iterate the first List, join seven Strings together and add that String to a second List? So you might have a 49‑element List which reduces to a 7‑element List each being 7 × as long?
What you are doing in the code above is simply iterating the first List and adding all its elements to the second List.
Do you know how to join Strings together? Are you using Java8?
Do you know anything about the StringBuilder class? Did you know you can use that to join several Strings, and delete them with the setLength method (sb.setLength(0))? Did you know you can get the current content of a StringBuilder with its toString method?
 
Ryan Kimu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. Sorry for my bad English. Yes i want to iterate over the first list which has 434 elements and join seven string together. I got stuck at the list.get() since i could not specify that i needed to get 7 elements from it. Yes I am using java8. Let me check out the StringBuilder class didn't know about it.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are in Java8 also look for the StringJoiner class and the String#join method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!