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 trim the capacity of an ArrayList?

For minimizing the storage used by an ArrayList to the number of its elements we can use the ArrayList.trimToSize() method call. In the code below we create an instance of ArrayList with the initial capacity set to 100. Later we only add five data into the list. To make the capacity of the ArrayList minimized we call the trimToSize() method.

package org.kodejava.util;

import java.util.ArrayList;

public class ListTrimToSize {
    public static void main(String[] args) {
        // Create an ArrayList with the initial capacity of 100.
        ArrayList<String> list = new ArrayList<>(100);
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        list.add("F");

        System.out.println("Size: " + list.size());

        // Trim the capacity of the ArrayList to the size
        // of the ArrayList. We can do this operation to reduce
        // the memory used to store data by the ArrayList.
        list.trimToSize();
    }
}

How do I convert java.util.Set into Array?

package org.kodejava.util;

import java.util.*;

public class SetToArray {
    public static void main(String[] args) {
        // Create a java.util.Set object and add some integers into the Set.
        Set<Integer> numberSet = new HashSet<>();
        numberSet.add(1);
        numberSet.add(2);
        numberSet.add(3);
        numberSet.add(5);
        numberSet.add(8);

        // Converting a java.util.Set into an array can be done by creating a
        // java.util.List object from the Set and then convert it into an array
        // by calling the toArray() method on the list object.
        List<Integer> numberList = new ArrayList<>(numberSet);
        Integer[] numbers = numberList.toArray(new Integer[0]);

        // Display the content of numbers array.
        for (int i = 0; i < numbers.length; i++) {
            Integer number = numbers[i];
            System.out.print(number + (i < numbers.length - 1 ? ", " : "\n"));
        }

        // Display the content of numbers array using the for-each loop.
        for (Integer number : numbers) {
            System.out.print(number + ", ");
        }
    }
}

How do I convert Set into List?

The code below gives you an example of converting a java.util.Set into a java.util.List. It has simply done by creating a new instance of List and pass the Set as the argument of the constructor.

package org.kodejava.util;

import java.util.*;

public class SetToList {
    public static void main(String[] args) {
        // Create a Set and add some objects into the Set.
        Set<Object> set = new HashSet<>();
        set.add("A");
        set.add(10L);
        set.add(new Date());

        // Convert the Set to a List can be done by passing the Set instance into
        // the constructor of a List implementation class such as ArrayList.
        List<Object> list = new ArrayList<>(set);
        for (Object o : list) {
            System.out.println("Object = " + o);
        }
    }
}

The output of the code snippet are:

Object = A
Object = 10
Object = Mon Oct 04 20:20:26 CST 2021

How do I sort items of an ArrayList?

This example shows you how we can sort items of an ArrayList using the Collections.sort() method. Beside accepting the list object to be sorted we can also pass a Comparator implementation to define the sorting behaviour such as sorting in descending or ascending order.

package org.kodejava.util;

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

public class ArrayListSortExample {
    public static void main(String[] args) {
        /*
         * Create a collections of colours
         */
        List<String> colours = new ArrayList<>();
        colours.add("red");
        colours.add("green");
        colours.add("blue");
        colours.add("yellow");
        colours.add("cyan");
        colours.add("white");
        colours.add("black");

        /*
         * We can sort items of a list using the Collections.sort() method.
         * We can also reverse the order of the sorting by passing the
         * Collections.reverseOrder() comparator.
         */
        Collections.sort(colours);
        System.out.println(Arrays.toString(colours.toArray()));

        colours.sort(Collections.reverseOrder());
        System.out.println(Arrays.toString(colours.toArray()));
    }
}

The code will output:

[black, blue, cyan, green, red, white, yellow]
[yellow, white, red, green, cyan, blue, black]

How do I convert collection to ArrayList?

package org.kodejava.util;

import java.util.ArrayList;
import java.util.LinkedList;

public class CollectionToArrayList {
    public static void main(String[] args) {
        // We create LinkedList collection type at put some values
        // in it. Here we put A, B, C and D letter into it.
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.push("A");
        linkedList.push("B");
        linkedList.push("C");
        linkedList.push("D");

        // Let say you want to convert it to other type of collection,
        // for instance here we convert it into ArrayList. To do it
        // we can pass the collection created above as a parameter to
        // ArrayList constructor.
        ArrayList<String> arrayList = new ArrayList<>(linkedList);

        // Now we have converted the collection into ArrayList and
        // printed what is inside.
        for (String s : arrayList) {
            System.out.println("s = " + s);
        }
    }
}

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 know if an ArrayList contains a specified item?

In this example we are going to learn how to find out if an ArrayList object contains the specified element. To check if an ArrayList object contains the specified element we can use the contains(Object o) method. This method returns a boolean true when the specified element is found in the ArrayList, otherwise return false. The method returns true if and only if the list contains at least one element, where the element equals to the item in the list.

Let’s see the code snippet below to demonstrate it.

package org.kodejava.util;

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

public class ArrayListContainsExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");

        // Check to see if the list contains "Item 1".
        String itemToFind = "Item 1";
        System.out.println("contains(" + itemToFind + "): " + list.contains(itemToFind));

        // Check to see if the list contains "Item 20".
        itemToFind = "Item 20";
        System.out.println("contains(" + itemToFind + "): " + list.contains(itemToFind));
    }
}

The output of the code snippet above are:

contains(Item 1): true
contains(Item 20): false

How do I know the size of ArrayList?

In this example we are going to learn how to obtain the size of an ArrayList object. As you might already know, a java.util.ArrayList is a class that we can use to create a dynamic sized array. We can add and remove elements from the ArrayList dynamically.

Because its elements can be added or removed at anytime, we might want to know the number of elements currently stored in this list. To obtain the size we can use the size() method. This method returns an int value that tells us the number of elements stored in the ArrayList object.

When the list contains more than Integer.MAX_VALUE elements this method returns Integer.MAX_VALUE.

package org.kodejava.util;

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

public class ArrayListSize {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        int size = list.size();
        System.out.println("List size = " + size);
    }
}

In the code snippet above we start creating an instance of ArrayList that can holds String values. As a good practice we should always use the interface as the type of the declared object, in this case we use the List interface. The <> is a diamond operator, started from JDK 7 you can use this operator so that you don’t need to repeat the generic type twice between the declaration and instantiation.

After we create the ArrayList object and add string elements to the list object, we get the size of the list by calling the size() method. We store the result in the size variable and print out its value. If you compile and run the code above you will get the following output:

List size = 3

How do I use ArrayList class?

In this example we will learn how to use the java.util.ArrayList class. An ArrayList is part of the Java Collection Framework. By using this class we can create a dynamic size array of data, which means we can add or remove elements from the array dynamically.

In the code below we will see the demonstration on how to create an instance of ArrayList, add some elements, remove elements and iterate through the entire ArrayList elements either using a for-loop or using the for-each syntax.

We can also see how to convert the ArrayList into an array object using the toArray() method. And we use the Arrays.toString() utility method when we want to print the content of an array.

When creating a class instance it is a good practice to use the interface as the type of variable instead of the concrete type directly. This can make us easily update our code if we don’t want to use ArrayList in the future.

And here is the code snippet:

package org.kodejava.util;

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

public class ArrayListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // Add items into ArrayList
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        // Remove the third item from ArrayList, first index = 0
        list.remove(2);

        // Iterate ArrayList item using for loop statement
        for (int i = 0; i < list.size(); i++) {
            String item = list.get(i);
            System.out.println("Item = " + item);
        }

        // Iterate ArrayList item using enhanced for statement
        for (String item : list) {
            System.out.println("Item = " + item);
        }

        // Iterate ArrayList item using forEach
        list.stream().map(item -> "Item = " + item).forEach(System.out::println);

        // Convert ArrayList into array of object
        String[] array = list.toArray(new String[0]);
        System.out.println("Items = " + Arrays.toString(array));
    }
}

Executing the program will give us the following output printed in our console.

Item = Item 1
Item = Item 2
Item = Item 1
Item = Item 2
Item = Item 1
Item = Item 2
Items = [Item 1, Item 2]