How do I know the minimum and maximum number in an array?

package org.kodejava.util;

import java.util.Arrays;
import java.util.Collections;

public class ArrayMinMax {
    public static void main(String[] args) {
        // Creates an array of integer numbers in it.
        Integer[] numbers = {8, 2, 6, 7, 0, 1, 4, 9, 5, 3};

        // To get the minimum or maximum value from the array we can
        // use the Collections.min() and Collections.max() methods.
        // But as this method requires a list type of data we need
        // to convert the array to list first.
        int min = Collections.min(Arrays.asList(numbers));
        int max = Collections.max(Arrays.asList(numbers));

        // Viola! we get the minimum and the maximum value from the
        // array.
        System.out.println("Min number: " + min);
        System.out.println("Max number: " + max);
    }
}

And here are the results:

Min number: 0
Max number: 9

How do I convert string to char array?

Here we have a small class that convert a string literal into an array, a character array. To do this we can simply use String.toCharArray() method.

package org.kodejava.lang;

public class StringToArrayExample {
    public static void main(String[] args) {
        // We have a string literal that contains the tag line of this blog.
        String literal = "Kode Java - Learn Java by Examples";

        // Now we want to convert or divided it into a small array of char.
        // To do this we can simply used String.toCharArray() method. This
        // method splits the string into an array of characters.
        char[] temp = literal.toCharArray();

        // Here we just iterate the char array and print it to our console.
        for (char c : temp) {
            System.out.print(c);
        }
    }
}

How do I convert Array to Collection?

package org.kodejava.util;

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

public class ArrayToListExample {
    public static void main(String[] args) {
        // Creates an array of object, in this case we create an
        // Integer array.
        Integer[] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};

        // Convert the created array above to collection, in this
        // example we convert it to a List.
        List<Integer> list = Arrays.asList(numbers);

        // We've got a list of our array here and iterate it.
        for (Integer number : list) {
            System.out.print(number + ", ");
        }
    }
}

How do I split a string?

Prior to Java 1.4 we use java.util.StringTokenizer class to split a tokenized string, for example a comma separated string. Starting from Java 1.4 and later the java.lang.String class introduce a String.split(String regex) method that simplify this process.

Below is a code snippet how to do it.

package org.kodejava.lang;

import java.util.Arrays;

public class StringSplit {
    public static void main(String[] args) {
        String data = "1,Diego Maradona,Footballer,Argentina";
        String[] items = data.split(",");

        // Iterates the array to print it out.
        for (String item : items) {
            System.out.println("item = " + item);
        }

        // Or simply use Arrays.toString() when print it out.
        System.out.println("item = " + Arrays.toString(items));
    }
}

The result of the code snippet:

item = 1
item = Diego Maradona
item = Footballer
item = Argentina
item = [1, Diego Maradona, Footballer, Argentina]

How do I sort an array of objects?

In this example we are going to learn how to sort an array of objects. We start by using an array of String objects as can be seen in the code snippet below. We sort the contents of the array using Arrays.sort() method and print the sorted result. It was really simple.

String names[] = {"Bob", "Mallory", "Alice", "Carol"};
Arrays.sort(names);
System.out.println("Names = " + Arrays.toString(names));

Next, we will sort an array of our own object. It is a bit different compared to sorting an array of primitives. The first rule is we need our object to implements the Comparable interface. This interface have one contract we need to implement, the compareTo() contract.

The basic rule of the compareTo() method is to return 0 when objects value are equals, 1 if this object value is greater and -1 if this object value is smaller. In the Person class below we simply call the String object compareTo() method. See the Person class below for more details.

package org.kodejava.util.support;

public class Person implements Comparable<Person> {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public int compareTo(Person person) {
        return this.name.compareTo(person.name);
    }

    public String toString() {
        return name;
    }
}

In the snippet below we create four Person objects. We sort the Person object based on their name using the Arrays.sort() method and print out the array values.

Person persons[] = new Person[4];
persons[0] = new Person("Bob");
persons[1] = new Person("Mallory");
persons[2] = new Person("Alice");
persons[3] = new Person("Carol");
Arrays.sort(persons);
System.out.println("Persons = " + Arrays.toString(persons));

This is the main class where you can run all the snippet above:

package org.kodejava.util;

import org.kodejava.util.support.Person;

import java.util.Arrays;

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

        Person[] persons = new Person[4];
        persons[0] = new Person("Bob");
        persons[1] = new Person("Mallory");
        persons[2] = new Person("Alice");
        persons[3] = new Person("Carol");
        Arrays.sort(persons);
        System.out.println("Persons = " + Arrays.toString(persons));
    }
}

This snippet will print the following output:

Names = [Alice, Bob, Carol, Mallory]
Persons = [Alice, Bob, Carol, Mallory]

How do I sort elements of an array?

package org.kodejava.util;

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // An array of random numbers
        int[] numbers = {3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55};
        System.out.println("Before: " + Arrays.toString(numbers));

        // We need to sort these array elements into a correct order
        // from the smallest to the greatest. We will use the Arrays
        // class on java.utils package to do the sort. The sort
        // method of this class are overloaded, so they can take
        // other type of array as well such as byte[], long[],
        // float[], Object[].
        Arrays.sort(numbers);
        System.out.println("After : " + Arrays.toString(numbers));

        // We can also do the sort only for the specified range of
        // array elements.
        float[] money = {1.05f, 99.8f, 3f, 4.55f, 7.23f, 6.50f};
        Arrays.sort(money, 3, money.length);

        // Here we display the sort result, the first and the second
        // element of the array is not included in the sort process.
        System.out.println("Money : " + Arrays.toString(money));
    }
}

And here are the results:

Before: [3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55]
After : [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Money : [1.05, 99.8, 3.0, 4.55, 6.5, 7.23]

How do I copy some items of an array into another array?

In the code snippet below we are going to learn how to use the System.arraycopy() method to copy array values. This method will copy array from the specified source array, starting from the element specified by starting position. The array values will be copied to the target array, placed at the specified start position in the target array and will copy values for the specified number of elements.

The code snippet below will copy 3 elements from the letters array and place it in the results array. The copy start from the third elements which is the letter U and will be place at the beginning of the target array.

package org.kodejava.lang;

public class ArrayCopy {
    public static void main(String[] args) {
        // Creates letters array with 5 chars inside it.
        String[] letters = {"A", "I", "U", "E", "O"};

        // Create an array to where we are going to copy
        // some elements of the previous array.
        String[] results = new String[3];

        // Copy 3 characters from letters starting from the
        // third element and put it inside result array
        // beginning at the first element
        System.arraycopy(letters, 2, results, 0, 3);

        // Just print out what were got copied, it will
        // contains U, E, and O
        for (String result : results) {
            System.out.println("result = " + result);
        }
    }
}

The output of the code snippet:

result = U
result = E
result = O

How do I convert a collection object into an array?

To convert collection-based object into an array we can use toArray() or toArray(T[] a) method provided by the implementation of Collection interface such as java.util.ArrayList.

package org.kodejava.util;

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

public class CollectionToArrayExample {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("Kode");
        words.add("Java");
        words.add("-");
        words.add("Learn");
        words.add("Java");
        words.add("by");
        words.add("Examples");

        String[] array = words.toArray(new String[0]);
        for (String word : array) {
            System.out.println(word);
        }
    }
}

Our code snippet result is shown below:

Kode
Java
-
Learn
Java
by
Examples

How do I convert an array into a collection object?

To convert array based data into List / Collection based we can use java.util.Arrays class. This class provides a static method asList(T... a) that converts array into List / Collection.

package org.kodejava.util;

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

public class ArrayAsListExample {
    public static void main(String[] args) {
        String[] words = {"Happy", "New", "Year", "2021"};
        List<String> list = Arrays.asList(words);

        for (String word : list) {
            System.out.println(word);
        }
    }
}

The results of our code are:

Happy
New
Year
2021

How do I compare if two arrays are equal?

Using Arrays.equals() methods we can compare if two arrays are equal. Two arrays are considered to be equal if their length, each element in both arrays are equal and in the same order to one another.

package org.kodejava.util;

import java.util.Arrays;

public class CompareArrayExample {
    public static void main(String[] args) {
        String[] abc = {"Kode", "Java", "Dot", "Org"};
        String[] xyz = {"Kode", "Java", "Dot", "Org"};
        String[] java = {"Java", "Dot", "Com"};

        System.out.println(Arrays.equals(abc, xyz));
        System.out.println(Arrays.equals(abc, java));
    }
}

The Arrays.equals() can be used to compare array of any primitive data type and array of Object. If you run this example you will have a result as follows:

true
false