Java Iterable to String iterableToString(Iterable objects, int limit)

Here you can find the source of iterableToString(Iterable objects, int limit)

Description

Returns a string representation of the iterable objects.

License

Open Source License

Parameter

Parameter Description
objects an iterable of objects to be turned into a string
limit the maximum number of objects from iterable to be used to build a string

Declaration

public static <T> String iterableToString(Iterable<T> objects, int limit) 

Method Source Code


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

public class Main {
    /**//ww w .  j a va 2 s  .c  o  m
     * Returns a string representation of the iterable objects. This is
     * used in debugging. The limit parameter is used to control how many
     * elements of the iterable are used to build the final string. Use
     * 0 or negative values, to include all.
     *
     * @param objects an iterable of objects to be turned into a string
     * @param limit the maximum number of objects from iterable to be used
     * to build a string
     */
    public static <T> String iterableToString(Iterable<T> objects, int limit) {
        StringBuilder builder = new StringBuilder().append("[");
        String sep = "";
        int head = (limit <= 0) ? Integer.MAX_VALUE : (limit + 1) / 2;
        int tail = (limit <= 0) ? 0 : limit - head;
        Iterator<T> iter = objects.iterator();
        while (iter.hasNext() && --head >= 0) {
            builder.append(sep).append(iter.next().toString());
            sep = ", ";
        }
        LinkedList<T> tailMembers = new LinkedList<T>();
        int seen = 0;
        while (iter.hasNext()) {
            tailMembers.add(iter.next());
            if (++seen > tail) {
                tailMembers.removeFirst();
            }
        }
        if (seen > tail) {
            builder.append(", ...");
        }
        for (T o : tailMembers) {
            builder.append(sep).append(o.toString());
            sep = ", ";
        }
        return builder.append("]").toString();
    }
}

Related

  1. iterableAsString(Iterable chars)
  2. iterableToString(Iterable iterable)
  3. iterableToString(Iterable list)
  4. iterableToString(Iterable charSequenceIterable)
  5. iterableToString(Iterable itrbl)
  6. toString(final Iterable iterable, final CharSequence delimiter)
  7. toString(Iterable c, String delim, String prefix, String suffix)
  8. toString(Iterable objects, String sep)
  9. toString(Iterable it, String separator)