How do I sort strings based on their length?

You can sort strings based on their length using the sort method combined with a custom comparator. In the code snippet below we are going to use the Arrays.sort() method. We pass an array of string to the sort() method and also a lambda expression as the custom comparator.

Here is how you’d do it in Java:

package org.kodejava.util;

import java.util.Arrays;

public class SortStringsExample {
    public static void main(String[] args) {
        String[] strings = {"Hello", "World", "Java", "is", "beautiful"};

        // Sort the array based on string length
        Arrays.sort(strings, (a, b) -> a.length() - b.length());

        // Print the sorted array
        Arrays.stream(strings).forEach(System.out::println);
    }
}

In this example, an array of strings is sorted in increasing order of their lengths. If you want to sort them in descending order, you can change the comparator to (a, b) -> b.length() - a.length().

The output of the code snippet above is:

is
Java
Hello
World
beautiful

How do I fill array with non-default value?

This code snippet will show you how to create array variable and initialized it with a non-default value. By default, when we create an array of something in Java all entries will have its default value. For primitive types like int, long, float the default value are zero (0 or 0.0). For reference types (anything that holds an object in it) will have null as the default value. For boolean variable it will be false.

If you want to initialize the array to different value you can use the Arrays.fill() method. This method will help you to set the value for every element of the array.

Let see the following code snippet as an example:

package org.kodejava.util;

import java.util.Arrays;

public class ArraysFillExample {
    public static void main(String[] args) {
        // Assign -1 to each element of numbers arrays
        int[] numbers = new int[5];
        Arrays.fill(numbers, -1);
        System.out.println("Numbers: " + Arrays.toString(numbers));

        // Assign 1.0f to each element of prices arrays
        float[] prices = new float[5];
        Arrays.fill(prices, 1.0f);
        System.out.println("Prices : " + Arrays.toString(prices));

        // Assign empty string to each element of words arrays
        String[] words = new String[5];
        Arrays.fill(words, "");
        System.out.println("Words  : " + Arrays.toString(words));

        // Assign 9 to each element of the multi array
        int[][] multi = new int[3][3];
        for (int[] array : multi) {
            Arrays.fill(array, 9);
        }
        System.out.println("Multi  : " + Arrays.deepToString(multi));
    }
}

In the code snippet above we utilize the Arrays.fill() utility method to assign value for each element of the int, float and String array. To change the default value of multidimensional array we can’t directly call the Arrays.fill() method. In the example we use for-loop to set each element of the sub-array using the Arrays.fill() method.

The output of the code snippet above are:

Numbers: [-1, -1, -1, -1, -1]
Prices : [1.0, 1.0, 1.0, 1.0, 1.0]
Words  : [, , , , ]
Multi  : [[9, 9, 9], [9, 9, 9], [9, 9, 9]]

How can I insert an element in array at a given position?

As we know an array in Java is a fixed-size object, once it created its size cannot be changed. So if you want to have a resizable array-like object where you can insert an element at a given position you can use a java.util.List object type instead.

This example will show you how you can achieve array insert using the java.util.List and java.util.ArrayList object. Let see the code snippet below.

package org.kodejava.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayInsert {
    public static void main(String[] args) {
        // Creates an array of integer value and prints the original values.
        Integer[] numbers = new Integer[]{1, 1, 2, 3, 8, 13, 21};
        System.out.println("Original numbers: " +
                Arrays.toString(numbers));

        // Creates an ArrayList object and initialize its values with the entire
        // content of numbers array. We use the add(index, element) method to add
        // element = 5 at index = 4.
        List<Integer> list = new ArrayList<>(Arrays.asList(numbers));
        list.add(4, 5);

        // Converts back the list into array object and prints the new values.
        numbers = list.toArray(new Integer[0]);
        System.out.println("After insert    : " + Arrays.toString(numbers));
    }
}

In the code snippet above the original array of Integer numbers will be converted into a List, in this case we use an ArrayList, we initialized the ArrayList by passing all elements of the array into the list constructor. The Arrays.asList() can be used to convert an array into a collection type object.

Next we insert a new element into the List using the add(int index, E element) method. Where index is the insert / add position and element is the element to be inserted. After the new element inserted we convert the List back to the original array.

Below is the result of the code snippet above:

Original numbers: [1, 1, 2, 3, 8, 13, 21]
After insert    : [1, 1, 2, 3, 5, 8, 13, 21]

How do I print the contents of an array variable?

You need to print the contents of an array variable. The long way to it is to user a loop to print each element of the array. To simplify this, you can use the Apache Commons Lang ArrayUtils.toString() method. This method can take any array as a parameter and print out the contents separated by commas and surrounded by curly brackets. When you need to print a specific string when the array is null, you can provide the second string argument to this method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsToString {
    public static void main(String[] args) {
        // Print an int array as string.
        int[] numbers = {1, 2, 3, 5, 8, 13, 21, 34};
        System.out.println("Numbers = " + ArrayUtils.toString(numbers));

        // Print string array as string.
        String[] grades = {"A", "B", "C", "D", "E", "F"};
        System.out.println("Grades = " + ArrayUtils.toString(grades));

        // Print a multidimensional array as string.
        int[][] matrix = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
        System.out.println("Matrix = " + ArrayUtils.toString(matrix));

        // Return "Empty" when the array is null.
        String[] colors = null;
        System.out.println("Colors = " + ArrayUtils.toString(colors, "None"));
    }
}

The output of the code snippet above:

Numbers = {1,2,3,5,8,13,21,34}
Grades = {A,B,C,D,E,F}
Matrix = {{0,1,2},{1,2,3},{2,3,4}}
Colors = None

If you are using the JDK 1.5, or later, you can actually use the java.util.Arrays class to do the same thing as the org.apache.commons.lang.ArrayUtils class does.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I clear the content of an array?

In this example you’ll learn how to clear or reset the content of an array. We can use the java.util.Arrays.fill() method to replace to content of each element in the array. In the example below we create two arrays, names and numbers array. We initialize these arrays with some values and then clear the value by assigning null to each element of the array using the Arrays.fill() method.

package org.kodejava.util;

import java.util.Arrays;

public class ArrayClear {
    public static void main(String[] args) {
        String[] names = {"Alice", "Bob", "Carol"};
        System.out.println("Names = " + Arrays.toString(names));

        // Replace the contents of the names array to null for each array
        // element.
        Arrays.fill(names, null);
        System.out.println("Names = " + Arrays.toString(names));

        Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println("Numbers = " + Arrays.toString(numbers));

        // Replace the contents of the numbers array to null for each
        // array element.
        Arrays.fill(numbers, null);
        System.out.println("Numbers = " + Arrays.toString(numbers));
    }
}

The output of the code snippet:

Names = [Alice, Bob, Carol]
Names = [null, null, null]
Numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Numbers = [null, null, null, null, null, null, null, null, null, null]