merge Join two String array - Java Collection Framework

Java examples for Collection Framework:Array Merge

Description

merge Join two String array

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String sep = "java2s.com";
        String[] a1 = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        String[] a2 = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(mergeJoin(sep, a1, a2));
    }/*from  w  w  w . j  a v  a 2 s. co  m*/

    public static String mergeJoin(String sep, String[] a1, String[] a2) {
        if (a1.length != a2.length) {
            System.out
                    .println("Unable to merge String arrays of different length!");
            return join(a1);
        }

        StringBuilder sb = new StringBuilder(a1[0]);
        sb.append(sep).append(a2[0]);
        for (int i = 1; i < a1.length; i++)
            sb.append(" ").append(a1[i]).append(sep).append(a2[i]);
        return sb.toString();
    }

    public static String join(Object[] array) {
        return join(" ", array);
    }

    public static String join(String sep, Object[] array) {
        StringBuilder sb = new StringBuilder(array[0].toString());
        for (int i = 1; i < array.length; i++)
            sb.append(sep).append(array[i].toString());
        return sb.toString();
    }

    public static String join(String[] array) {
        return join(" ", array);
    }

    public static String join(String sep, String[] array) {
        StringBuilder sb = new StringBuilder(array[0]);
        for (int i = 1; i < array.length; i++)
            sb.append(sep).append(array[i]);
        return sb.toString();
    }

    public static String join(int[] array) {
        return join(" ", array);
    }

    public static String join(String sep, int[] array) {
        StringBuilder sb = new StringBuilder(Integer.toString(array[0]));
        for (int i = 1; i < array.length; i++)
            sb.append(sep).append(array[i]);
        return sb.toString();
    }

    public static String join(double[] array) {
        return join(" ", array);
    }

    public static String join(String sep, double[] array) {
        StringBuilder sb = new StringBuilder(Double.toString(array[0]));
        for (int i = 1; i < array.length; i++)
            sb.append(sep).append(array[i]);
        return sb.toString();
    }
}

Related Tutorials