Converts an array of ints into sets of comma-delimited value strings, each with a maximum number of numbers in. - Java java.lang

Java examples for java.lang:String Array

Description

Converts an array of ints into sets of comma-delimited value strings, each with a maximum number of numbers in.

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.IOException;

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        int[] values = new int[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int max = 42;
        char mask = 'a';
        System.out.println(java.util.Arrays.toString(toChunkedStringArrays(
                values, max, mask)));/* w w w  .j a  v a 2  s.com*/
    }

    /**
     * Converts an array of ints into sets of comma-delimited value strings,
     * each with a maximum number of numbers in. Will return only one group if
     * max is zero. Where values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] and max = 4,
     * the return value will equal ["1,2,3,4", "5,6,7,8", "9,10,11"].
     * 
     * The character mask will only be used when its value is other than '0'.
     */
    public static String[] toChunkedStringArrays(final int[] values,
            final int max, final char mask) {
        if (values.length == 0)
            return new String[] {};

        String[] groups = new String[max != 0 ? values.length / max : 1];
        StringBuffer ints = new StringBuffer();

        for (int i = 0; i < values.length; i++) {
            if (mask != '0')
                ints.append(mask);
            else
                ints.append(values[i]);

            if (i + 1 != values.length && (max == 0 || (i + 1) % max != 0))
                ints.append(',');
            else {
                groups[max != 0 ? (i / max) - 1 : 0] = ints.toString();
                ints = new StringBuffer();
            }
        }

        return groups;
    }

 
}

Related Tutorials