如何在不使用括号的情况下呈现集合值

时间:2017-06-24 10:17:53

标签: jsf collections

我使用Java创建了一个JSF Web应用程序,并使用集合对象来表示“一对多”关系。现在我想通过显示集合来显示这种关系。集合以此处的样式[item1, item2, item3]显示。但我希望它们以item1, item2, item3的形式列在没有括号的位置。我不允许更改AbstractCollection的toString方法。是否有可能在另一个类中覆盖AbstractCollection的toString方法?或者是否有其他方式以我想要的形式显示集合?

2 个答案:

答案 0 :(得分:1)

您可以覆盖所有AbstractCollection SubClasses上的toString()方法。

假设你有一个班级MyCollection<T> extends AbstractCollection<T>,你可以写:

@Override
public String toString() {
    return this.stream().map(o -> o.toString()).collect(Collectors.joining(","));
}

如果您愿意,可以使用util方法打印所有集合,如下所示:

public <T> String printAbstractCollections(AbstractCollection<T> c) {
        return c.stream().map(o -> o.toString()).collect(Collectors.joining(","));
}

答案 1 :(得分:1)

您需要为您的收藏集创建装饰器,如果您不想标准toString(),只需将您的收藏集放到PrettyPrintCollection

public final class PrettyPrintCollection<E> implements Collection<E> {
    private final Collection<E> collection;

    public PrettyPrintCollection(Collection<E> collection) {
        this.collection = collection;
    }

    @Override
    public int size() {
        return collection.size();
    }

    @Override
    public boolean isEmpty() {
        return collection.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return collection.contains(o);
    }

    @Override
    public Iterator<E> iterator() {
        return collection.iterator();
    }

    @Override
    public Object[] toArray() {
        return collection.toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return collection.toArray(a);
    }

    @Override
    public boolean add(E e) {
        return collection.add(e);
    }

    @Override
    public boolean remove(Object o) {
        return collection.remove(o);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return collection.contains(c);
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        return collection.addAll(c);
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        return collection.removeAll(c);
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return collection.retainAll(c);
    }

    @Override
    public void clear() {
        collection.clear();
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        Iterator<E> elements = collection.iterator();
        while (elements.hasNext()) {
            builder.append(elements.next());
            if (elements.hasNext()) {
                builder.append(", ");
            }
        }
        return builder.toString();
    }
}

并测试它

public class Main {

    public static void main(String[] args) {
        Collection<String> collection = Arrays.asList("a", "b", "c");
        System.out.println(collection);
        System.out.println(new PrettyPrintCollection<>(collection));
    }
}

输出将是:

[a, b, c] 
a, b, c