如何为集合实现toString()?

时间:2014-09-03 12:34:05

标签: java

我经常需要打印列表或地图,但我不喜欢它们默认的toString()方法的输出。例如HashMap#toString()输出如下内容:

{key-1=value-1, key-2=value-2, key-3=value-3}

但我希望输出如下:

key-1 = value-1, key-2 = value-2, key-3 = value-3

我创建了一个扩展HashMap的自定义类,并编写了我自己的toString()方法,这导致了我的真正问题:

public final class CustomMap<K, V> extends HashMap<K, V> {

    private static final long serialVersionUID = 1493227382148892732L;

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();

        final Iterator<Map.Entry<K, V>> entryIterator = entrySet().iterator();

        if (entryIterator.hasNext()) {
            final Map.Entry<K, V> entry = entryIterator.next();

            builder.append(entry.getKey());
            builder.append(" = ");
            builder.append(entry.getValue());
        }

        while (entryIterator.hasNext()) {
            final Map.Entry<K, V> entry = entryIterator.next();

            builder.append(", ");
            builder.append(entry.getKey());
            builder.append(" = ");
            builder.append(entry.getValue());
        }

        return builder.toString();
    }

}

如您所见,我有重复代码,因为,部分必须省略一次。那么如何在没有重复代码的情况下将其重写为一种快速有效的方法呢?

3 个答案:

答案 0 :(得分:2)

可以使用布尔值轻松解决:

    final Iterator<Map.Entry<K, V>> entryIterator = entrySet().iterator();
    boolean first = true;
    while (entryIterator.hasNext()) {
        final Map.Entry<K, V> entry = entryIterator.next();
        if (!first)
            builder.append(", ");
        else
            first=false;
        builder.append(entry.getKey());
        builder.append(" = ");
        builder.append(entry.getValue());
    }

另一种选择是使用Java 8 StringJoiner:

    StringJoiner sj = new StringJoiner(",");
    while (entryIterator.hasNext()) {
        final Map.Entry<K, V> entry = entryIterator.next();
        sj.add(entry.getKey() + " = " + entry.getValue());
    }
    return sj.toString();

答案 1 :(得分:0)

不要在HashMap

上扩展String.subString()而是使用HashMap.toString()方法
String s=yourMap.toString();//eg-"{key-1=value-1, key-2=value-2, key-3=value-3}"
System.out.println(s.substring(1,s.length()-1)); 

输出: -key-1 = value-1,key-2 = value-2,key-3 = value-3

创建删除最后一个逗号的方法

public StringBuilder removeComma(StringBuilder sbf) {
                if (sbf.charAt(sbf.length() - 1) == ',') {
                    sbf.deleteCharAt(sbf.length() - 1);
                }
                return sbf;
            }


public String toString() {
        final StringBuilder builder = new StringBuilder();
        final Iterator<Map.Entry<K, V>> entryIterator = entrySet().iterator();
        while (entryIterator.hasNext()) {
            final Map.Entry<K, V> entry = entryIterator.next();
            builder.append(entry.getKey()).append(" = ").append(entry.getValue()).append(",");
        }
        return removeComma(builder).toString();
      }

另一个选项使用变量

 public String toString() {
                String comma="";//initaly empty
                final StringBuilder builder = new StringBuilder();
                final Iterator<Map.Entry<K, V>> entryIterator = entrySet().iterator();
                while (entryIterator.hasNext()) {
                    final Map.Entry<K, V> entry = entryIterator.next();
                    builder.append(comma).append(entry.getKey()).append(" = ").append(entry.getValue());
                    comma=",";//set value of comma
                }
                return removeComma(builder).toString();
              }

答案 2 :(得分:0)

我刚检查了AbstractCollection的来源,就像这样:

public final class CustomMap<K, V> extends HashMap<K, V> {

    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 1493227382148892732L;

    @Override
    public String toString() {
        final Iterator<Map.Entry<K, V>> entryIterator = entrySet().iterator();

        if (!entryIterator.hasNext()) {
            return "";
        }

        final StringBuilder builder = new StringBuilder();

        for (;;) {
            final Map.Entry<K, V> entry = entryIterator.next();

            builder.append(entry.getKey());
            builder.append(" = ");
            builder.append(entry.getValue());

            if (!entryIterator.hasNext()) {
                return builder.toString();
            }

            builder.append(", ");
        }
    }

}

这看起来很聪明,循环中只有一个检查。