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.example.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, 2, 3, 8, 13, 21};
        System.out.println("Original numbers: " +
            Arrays.toString(numbers));

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

        // Converts back the list into array object and prints the new values.
        numbers = list.toArray(new Integer[list.size()]);
        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, by adding all elements of the array into the list using the List.addAll() method. The Arrays.asList() can be use 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, 2, 3, 8, 13, 21]
After insert    : [1, 2, 3, 5, 8, 13, 21]

How do I reverse the order of array elements?

In this code snippet you’ll learn how to reverse the order of array elements. To reverse to element order will be using the Collections.reverse() method. This method requires an argument with List type. Because of this we need to convert the array to a List type first. We can use the Arrays.asList() to do the conversion. And then we reverse it. To convert the List back to array we can use the Collection.toArray() method.

Let’s see the code snippet below:

package org.kodejava.example.util;

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

public class ArrayReverse {
    public static void main(String[] args) {
        // Creates an array of Integers and print it out.
        Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println("Arrays.toString(numbers) = " + Arrays.toString(numbers));

        // Convert the int arrays into a List.
        List numberList = Arrays.asList(numbers);

        // Reverse the order of the List.
        Collections.reverse(numberList);

        // Convert the List back to arrays of Integers
        // and print it out.
        numberList.toArray(numbers);
        System.out.println("Arrays.toString(numbers) = " + Arrays.toString(numbers));
    }
}

The output of the code snippet above is:

Arrays.toString(numbers) = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Arrays.toString(numbers) = [8, 7, 6, 5, 4, 3, 2, 1, 0]

How do I create ZapfDingbats List in iText?

This example show you how to use the com.itextpdf.text.ZapfDingbatsList class to create a ZapfDingbatsList list using the iText pdf library.

package org.kodejava.example.itextpdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class ZapfDingbatsListDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("ZapfDingbats.pdf"));
            doc.open();

            // Create a ZapfDingbatsList with char number 50
            List zapf1 = new ZapfDingbatsList(50);
            zapf1.add(new ListItem("Item 1"));
            zapf1.add(new ListItem("Item 2"));
            zapf1.add(new ListItem("Item 3"));
            doc.add(zapf1);

            // Create a ZapfDingbatsList with char number 55 and indent
            // it by 30.
            List zapf2 = new ZapfDingbatsList(55, 30);
            zapf2.add(new ListItem("Item 1"));
            zapf2.add(new ListItem("Item 2"));
            zapf2.add(new ListItem("Item 3"));
            doc.add(zapf2);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>

How do I create a List in iText?

You can create a list in iText using the com.itextpdf.text.List. This class represent a list. The list item is created using the com.itextpdf.text.ListItem. You can create an ordered list or unordered list. To create ordered list pass the List.ORDERED as the parameter to class List. To create an unordered list pass the List.UNORDERED.

Let’s see an example below:

package org.kodejava.example.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class ListDemo {
    public static void main(String[] args) {
        Document document = new Document();
        try {
            PdfWriter.getInstance(document, new FileOutputStream("ListDemo.pdf"));
            document.open();

            List ordered = new List(List.ORDERED);
            ordered.add(new ListItem("Item 1"));
            ordered.add(new ListItem("Item 2"));
            ordered.add(new ListItem("Item 3"));
            document.add(ordered);

            List unordered = new List(List.UNORDERED);
            unordered.add(new ListItem("Item 1"));
            unordered.add(new ListItem("Item 2"));
            unordered.add(new ListItem("Item 3"));
            document.add(unordered);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>

How do I retrieve particular object from LinkedList?

The example show you how to retrieve particular object from LinkedList using the indexOf() method.

package org.kodejava.example.util;

import java.util.List;
import java.util.LinkedList;

public class LinkedListIndexOf {
    public static void main(String[] args) {
        List<String> names = new LinkedList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Carol");
        names.add("Mallory");

        // Search for Carol using the indexOf method. This method
        // returns the index of the object when found. If not found
        // -1 will be returned.
        int index = names.indexOf("Carol");
        System.out.println("Index = " + index);

        // We can check to see if the index returned is in the range
        // of the LinkedList element size.
        if (index > 0 && index < names.size()) {
            String name = names.get(index);
            System.out.println("Name  = " + name);
        }
    }
}

The program prints the following output:

Index = 2
Name  = Carol

How do I iterate LinkedList elements using ListIterator?

This example show you how to use the ListIterator interface to iterate elements of a LinkedList.

package org.kodejava.example.util;

import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;

public class LinkedListListIterator {
    public static void main(String[] args) {
        List<String> grades = new LinkedList<>();
        grades.add("A");
        grades.add("B");
        grades.add("C");
        grades.add("D");
        grades.add("E");

        // Retrieves object from LinkedList using the ListIterator
        // interface.
        ListIterator li = grades.listIterator();
        while (li.hasNext()) {
            System.out.println("Grades: " + li.next());
            System.out.println("    hasPrevious  : " + li.hasPrevious());
            System.out.println("    hasNext      : " + li.hasNext());
            System.out.println("    previousIndex: " + li.previousIndex());
            System.out.println("    nextIndex    : " + li.nextIndex());
        }
    }
}

The program will prints the following output:

Grades: A
    hasPrevious  : true
    hasNext      : true
    previousIndex: 0
    nextIndex    : 1
Grades: B
    hasPrevious  : true
    hasNext      : true
    previousIndex: 1
    nextIndex    : 2
Grades: C
    hasPrevious  : true
    hasNext      : true
    previousIndex: 2
    nextIndex    : 3
Grades: D
    hasPrevious  : true
    hasNext      : true
    previousIndex: 3
    nextIndex    : 4
Grades: E
    hasPrevious  : true
    hasNext      : false
    previousIndex: 4
    nextIndex    : 5

How do I iterate LinkedList elements using Iterator?

This example show you how to use the Iterator interface to iterate elements of a LinkedList.

package org.kodejava.example.util;

import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;

public class LinkedListIterator {
    public static void main(String[] args) {
        List<String> grades = new LinkedList<>();
        grades.add("A");
        grades.add("B");
        grades.add("C");
        grades.add("D");
        grades.add("E");

        // Iterates elements in LinkedList using Iterator.
        Iterator iterator = grades.iterator();
        while (iterator.hasNext()) {
            System.out.println("Grade: " + iterator.next());
        }
    }
}

This program prints the following output:

Grade: A
Grade: B
Grade: C
Grade: D
Grade: E

How do I create a LinkedList?

A linked list is a fundamental data structure in programming. It can stores data and a references to the next and/or to the previous node. There can be a singly linked list, a doubly linked list and a circularly linked list.

The code below show you how to use the java.util.LinkedList class to create a linked list. In the example we create a LinkedList to store a string object using the add(Object o) method. After create the list we iterate the list and print out the contents.

package org.kodejava.example.util;

import java.util.List;
import java.util.LinkedList;

public class LinkedListCreate {
    public static void main(String[] args) {
        // Creates a new instance of java.util.LinkedList and
        // adds five string object into the list.
        List<String> grades = new LinkedList<>();
        grades.add("A");
        grades.add("B");
        grades.add("C");
        grades.add("E");
        grades.add("F");

        // Iterates the LinkedList object using the for each
        // statement.
        for (String grade : grades) {
            System.out.println("Grade: " + grade);    
        }
    }
}

This program will produce the following output:

Grade: A
Grade: B
Grade: C
Grade: E
Grade: F

How do I convert Set into Array?

package org.kodejava.example.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[numberList.size()]);

        // 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 simply done by creating a new instance of List and pass the Set as the argument of the constructor.

package org.kodejava.example.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);
        }
    }
}