Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Printing LinkedList without square brackets?

This is a fairly simple question. When you print out a LinkedList, like so:

System.out.println(list);

It prints it out, surrounding the list in square brackets like this:

[thing 1, thing 2, thing 3]

Is there a way I can print it out without the square brackets?

like image 537
Blackvein Avatar asked Oct 21 '11 19:10

Blackvein


People also ask

How do you remove square brackets from a Hashset in Java?

replaceAll("(^\\[|\\]$)", ""); In the above code first we are removing first square bracket then we are removing the second square bracket and replacing i with empty string. Now the output string has array list with no square brackets. If you have any doubt or suggestions then leave it in comment box.

How do you print a LinkedList java?

Print LinkedList using a for loop Just as with other Lists, a Linked List starts from index 0 , and we can use the size() method to get the total number of elements in the List. For each iteration of the for loop, pass the index to the get(index) method, which will return the element in the specific address.


3 Answers

Yes - iterate the list and print it (with comma after each, but the last element). However, there are utils to help:

Guava:

String result = Joiner.on(", ").join(list);

commons-lang:

String result = StringUtils.join(list, ", ");

And one note: don't rely on the .toString() method of any object. It is not meant for displaying the object to users, or to be used as a predefined format - it is meant mainly for debugging purposes.

like image 113
Bozho Avatar answered Sep 30 '22 14:09

Bozho


A quick-and-dirty answer is:

String s = list.toString();
System.out.println(s.substring(1, s.length()-1));
like image 37
Sean Owen Avatar answered Sep 30 '22 14:09

Sean Owen


You could subclass LinkedList and override it's toString() method, but that seems a little excessive. Instead, iterate over it's elements and construct a String with either a StringBuilder, or a StringBuffer(if concurrency is an issue).

Note:
I suggest you don't follow the answer provided by @Sean Owen, since that's implementation-dependent and therefore, fragile.

like image 41
mre Avatar answered Sep 30 '22 16:09

mre