简体   繁体   中英

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?

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.

A quick-and-dirty answer is:

String s = list.toString();
System.out.println(s.substring(1, s.length()-1));

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.

If you're into groovy , there's no need to import anything, just do:

list = ["thing 1", "thing 2", "thing 3"]    
println list.collect { i -> "$i" }.join(', ')

thing 1, thing 2, thing 3


Same goes with Map collection:

map = [I:"James Bond", love:"rock N roll", id:"007"]
println map.collect { k,v -> "$k = $v" }.join('\n')

I = James Bond

love = rock N roll

id = 007

This is the default implementation of the toString() on LinkedList. You could extend LinkedList to provide your own implementation or use composition and just implement the java.util.List interface.

public class MyLinkedList<E> implements List<E>
{
   private final List<E> delegate;

   public MyLinkedList(List<E> list)
   {
      delegate = list;
   }

   /**
    * @return see overriden class or implemented interface
    * @see java.lang.Object#toString()
    */
   @Override
   public String toString()
   {
      return "My special toString() method";
   }

   // implement rest of the java.util.List interface

Modified from AbstractCollection.java :

   /*
    * @return a string representation of a collection
    */
   public static final String collectionToString(Collection c) {
       Iterator<E> it = c.iterator();
       if (! it.hasNext())
           return "";

       StringBuilder sb = new StringBuilder();
       for (;;) {
           E e = it.next();
           sb.append(e == c ? "(this Collection)" : e);
           if (! it.hasNext())
               return sb.toString();
           sb.append(',').append(' ');
       }
   }
StrBuilder builder = new StrBuilder(); // apache commons lang.
for (Object object : yourList)
{
  builder.appendSeperator(", ");
  builder.append(object.toString());
}

System.out.println(builder.toString());

You can grab the String returned by the .toString() method and remove the first and last character, or make your own list class and override the .toString() method to iterate through the list and print the elements without the brackets. Or you can do it as an anonymous class like:

List<String> list = new List<String>() {
    public String toString() {
        // Custom To String Stuff Here
    }
};

And of course I'm too slow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM