riorio
riorio

Reputation: 6816

Printing 2 arrays side by size when their length is different

Say we have these 2 arrays with different length:

String [] names = {"Sam", "Ben", "Nancy"}
String [] ages= {"5", "10"}

And I want to display them side by side:

Sam 5
Ben 10
Nancy --

I know I can do a for loop on both arrays till the shorter array ends and then to print the remaining part of the longer array with the corresponding -- sign.

Is there a better way to do it?

Upvotes: 0

Views: 923

Answers (4)

Umer Farooq
Umer Farooq

Reputation: 782

You can also do this using java stream

IntStream.range(0, Math.max(names.length, ages.length)).forEach(i->{
      System.out.format("%s %s\n", (i >= names.length) ? "--" : names[i], (i >= ages.length) ? "--" : ages[i] );
    });

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

Based on Neng Liu's response, I modified this work work with any number of String arrays.

The following line:

int[] lengths = maxValueLengths(arrays); // See function below.

// ...

System.out.printf(String.format("%%-%ds", lengths[col]), arrays[col][row]);

Pads the value with a number of spaces equal to the max value length in the column. For example, if the max value length in column one is 5, then the format "%-5s" will be used to apply (spaces) left-justification to the value.

This could simply be used instead, but will not provided nice padding for alignment.

System.out.print(arrays[col][row]);

Full Example

public class MultiArrayPrinter {
    public final static String EMPTY_VALUE   = "--";
    public final static String COL_SEPARATOR = "\t";

    public static void main(String[] args) {
        String[] names = { "Sam", "Ben", "Nancy" };
        String[] ages  = { "5", "10" };

        MultiArrayPrinter.printArrays(names, ages);
    }

    public static void printArrays(String[]... arrays) {
        int   longer  = longestArrayLength(arrays); // 3
        int[] lengths = maxValueLengths(arrays);    // [ 5, 2 ]

        for (int row = 0; row < longer; row++) {
            for (int col = 0; col < arrays.length; col++) {
                if (row < arrays[col].length) {
                    System.out.printf(String.format("%%-%ds", lengths[col]), arrays[col][row]);
                } else {
                    System.out.print(EMPTY_VALUE);
                }
                if (col < arrays.length - 1) {
                    System.out.print(COL_SEPARATOR);
                }
            }
            System.out.print(System.lineSeparator());
        }
    }

     private static int[] maxValueLengths(String[]... arrays) {
        int[] lengths = new int[arrays.length];
        for (int i = 0; i < arrays.length; i++) {
            int maxLength = 0;
            for (int j = 0; j < arrays[i].length; j++) {
                if (arrays[i][j].length() > maxLength) {
                    maxLength = arrays[i][j].length();
                }
            }
            lengths[i] = maxLength;
        }
        return lengths;
    }

    private static int longestArrayLength(String[]... arrays) {
        int maxLength = 0;
        for (String[] array : arrays) {
            if (array.length > maxLength) {
                maxLength = array.length;
            }
        }
        return maxLength;
    }
}

Output

Sam     5
Ben     10
Nancy   --

Upvotes: 0

Marcin Grudziąż
Marcin Grudziąż

Reputation: 23

try this:

  for (int i = 0; i < Math.max(names.length, ages.length); i++){
    System.out.println(((i >= names.length) ? "--" : names[i]) + " " + ((i >= ages.length) ? "--" : ages[i]));
}

Upvotes: 1

xingbin
xingbin

Reputation: 28269

Before printing elements, check if it is out of bound:

public static void main(String[] args) {
    String [] names = { "Sam", "Ben", "Nancy" };
    String [] ages  = { "5", "10" };

    int longer = Integer.max(names.length, ages.length);

    for (int index = 0; index < longer; index++) {
        if (index < names.length) {
            System.out.print(names[index]);
        } else {
            System.out.print("--");
        }
        System.out.print(" ");
        if (index < ages.length) {
            System.out.println(ages[index]);
        } else {
            System.out.println("--");
        }
    }
}

Upvotes: 2

Related Questions