Creates a string representation according to the java.util.AbstractCollection#toString() method, with a limited length param. - Java java.util

Java examples for java.util:Collection Operation

Description

Creates a string representation according to the java.util.AbstractCollection#toString() method, with a limited length param.

Demo Code


//package com.java2s;
import java.util.Collection;
import java.util.Iterator;

public class Main {
    public static void main(String[] argv) {
        Collection coll = java.util.Arrays.asList("asdf", "java2s.com");
        int limit = 42;
        System.out.println(toLimitLengthString(coll, limit));
    }/*  www.j  a  v a2s.  c  o  m*/

    /**
     * Creates a string representation according to the {@link java.util.AbstractCollection#toString()}
     * method, but with a limited length param.
     * Such that, if limit is >= the collection's size the original representation is returned,
     * otherwise the collection's representation ends after the limit-th element with
     * ",...]".
     *
     * @param <E> the type of the elements in the collection
     * @param coll the collection to transformed into string
     * @param limit the maximum number of elements to represented in the string
     * @return the (limited length) string representation
     */
    public static <E> String toLimitLengthString(final Collection<E> coll,
            final int limit) {
        if (fallBackToStandardImplementation(coll, limit)) {
            return coll.toString();
        }
        final Iterator<E> iter = coll.iterator();

        final StringBuilder sb = new StringBuilder();
        sb.append('[');

        final int min = Math.min(coll.size(), limit);
        for (int i = 0; i < min; i++) {
            final E e = iter.next();
            sb.append(e == coll ? "(the collection itself)" : e); // recursive check, when an element is the collection itself
            if (!iter.hasNext() || i + 1 >= min) {
                return sb.append(",...]").toString();
            }
            sb.append(", ");
        }
        return "[]";
    }

    private static <E> boolean fallBackToStandardImplementation(
            final Collection<E> coll, final int limit) {
        return limit >= coll.size() || limit < 0 || coll.isEmpty();
    }
}

Related Tutorials