• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Convert ArrayList<Integer> to a String without the [] brackets

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I currently have an ArrayList<Integer> that I am trying to convert into a String so that I can output it to a JLabel in my GUI class.




So let's say the numbers ArrayList has the contents 1, 3, 7. The above method returns [1,3,7]
I want to be able to convert this into a String so that it will output to the JLabel as 1, 3, 7 instead of being surrounded with the [ ] brackets.

Thanks
 
Greenhorn
Posts: 7
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi to achieve this you could either you will need to to iterate over over your ArrayList and append each element to a StringBuilder Object.
 
Bartender
Posts: 2911
150
Google Web Toolkit Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Conor Niall wrote:
I currently have an ArrayList<Integer> that I am trying to convert into a String so that I can output it to a JLabel in my GUI class.




The toString method is a utility method used for debugging purposes. It has a custom implementation on a per-class basis. Hence, you should not typically use it to achieve the end goal or output. In this case, the ArrayList class gives you a debugging output for the items it contains, it does so by creating a comma separated list within square brackets.

If you want to "convert" this ArrayList to a customized output String, there isn't a direct method to give you the output you want, a code logic is required to be written. As Jean Claude suggested, you need to iterate over the elements in the list.

Welcome to coderanch Jean Claude Uwimpuhwe
 
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just get the value returned from the toString() method and then use the String.substring(...) method to get whatever part of the text you want.
 
Conor Niall
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks guys,
I've ended up going with what Jean Claude suggested, and after a bit of research, I've come up with this:



It seems to work so far.
Any tips for improving this even more? Or is this as efficient as it's gonna get?

Cheers
 
Saloon Keeper
Posts: 10779
86
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Instead of a lot of String concatenation use a StringBuilder with append() method. At the end return the StringBuilder variable with the toString() method.
(NEVER MIND)
 
Marshal
Posts: 4525
572
VSCode Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Conor Niall wrote:Any tips for improving this even more?


Your string will have spaces after the last integer.  Since you know the size of the array, you could add some logic to only append the spaces when you are not dealing with the last element of the array.
 
Sheriff
Posts: 17652
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Conor Niall wrote:Any tips for improving this even more? Or is this as efficient as it's gonna get?


Worry less about efficiency. Worry more about clarity and conciseness. When you go for the latter, the former usually follows.

Use better names that explain their intent/purpose/role, not their data types.  The name myNumbersInt is a bad name.

Make your code as tight and self-enclosed as possible. By referencing a variable that's outside your method (the private numbers field), you are making your method less self-contained. Prefer to pass the List of numbers as a parameter to the method.

You can use an enhanced for loop instead of the regular for-loop. This will make the code less verbose.  

Prefer to declare data types using interface (List<Integer>), if there is one, not the implementation (ArrayList<Integer>).

You can chain calls to StringBuffer.append().

Declare methods to have the narrowest access as possible. Does this method really have to be public? I usually start with private, then promote as I find justification to do so. If you promote this method to public, why make it an instance method?  If it takes all the information it needs as a parameter and does not need anything specific to a current instance of the class, why not declare the method as a static method?  I'm not advocating that you should try to make all methods static, mind you. I'm just saying that if a method does not have any code that is dependent on the characteristics of an instance of the class that it's in, it really has no business being an instance method.  Instance methods should rely on at least one instance field of the class that it belongs to.

Here's a tighter version of the code you wrote, with all of the above applied.

Pretty amazing how much nuance there is in just a few lines of code, right?
 
Junilu Lacar
Sheriff
Posts: 17652
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ron McLeod wrote:Your string will have spaces after the last integer.  Since you know the size of the array, you could add some logic to only append the spaces when you are not dealing with the last element of the array.


Or you could just cut to the chase and trim() the String before you return it.  Same idea if you wanted to use a ", " to separate the numbers: Just append to all elements and chop off the last couple of characters you appended using StringBuilder.substring()
 
salvin francis
Bartender
Posts: 2911
150
Google Web Toolkit Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, since trim does a good job here, I would agree with the same. But if it had to be comma,
 
Junilu Lacar
Sheriff
Posts: 17652
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

salvin francis wrote:Well, since trim does a good job here, I would agree with the same. But if it had to be comma,


If you had 100 numbers in that list, how many times do you have to evaluate that if statement inside the loop? 1000 numbers? 1 million numbers?

How many times do you have to chop off one or two characters from the value before you return it? What if you had 1000 numbers? 1 million numbers?

I don't normally think about optimization and performance much but when it's as obvious as this, I go for it.
 
Ron McLeod
Marshal
Posts: 4525
572
VSCode Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

salvin francis wrote:But if it had to be comma


Based on Junilu's suggestion, you could just simply chop-off the delimiter's length off the end of the string.
 
Marshal
Posts: 79392
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let's try some Java8 coding. As we all know you can get a Stream out of every List (well, more precisely every Collection) with its stream() method. Since you are starting off with a List<Integer>, that will give you a Stream<Integer>. You can get a String out of an Integer several ways: let's try String::valueOf. That is a method reference; the JVM will interpret that as, “Apply that method to every element of the Stream.” You now have a Stream<String>.
You can join those Strings with the collect method; when you pass a Collector to it as an argument, you get all sorts of results. If you want a String, let't try this Collector, which is returned ready‑made by this method of the Collectors class. Pass ", " as an argument and it joins with commas between successive elements. You will find that last method is overloaded for different display options. You can of course use a different delimiter.But I am surprised you aren't happy with something like this:-
 
Junilu Lacar
Sheriff
Posts: 17652
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ron McLeod wrote:Based on Junilu's suggestion, you could just simply chop-off the delimiter's length off the end of the string.


Just so you know, this is something I picked up in the very old days of working with dBase II programs.

Here's another gem: How do you quickly get a String of N characters?

You might try this:

But this gets you there in fewer iterations:

Actually, I think I prefer:

In dBase, it was done with a while loop and plain old string concatenation. Same idea though.
 
reply
    Bookmark Topic Watch Topic
  • New Topic