How do I use the List.sort() method?

The List.sort() method was introduced in Java 8. This method sorts the elements of the list on the basis of the given Comparator. If no comparator is provided, it will use the natural ordering of the elements (only if the elements are Comparable).

Let’s take a look at an example where we sort a list of integers in ascending order:

package org.kodejava.util;

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

public class ListSortExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(3);
        numbers.add(1);
        numbers.add(4);
        numbers.add(1);
        numbers.add(5);

        // Use sort() to sort the numbers in ascending order
        numbers.sort(null);

        System.out.println(numbers); 
    }
}

Outputs:

[1, 1, 3, 4, 5]

You can also pass a Comparator to List.sort(). Here’s an example where we sort a list of strings by their length:

package org.kodejava.util;

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

public class ListSortOtherExample {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("rat");
        words.add("elephant");
        words.add("cat");
        words.add("mouse");

        // Comparator for comparing string lengths
        Comparator<String> lengthComparator = (s1, s2) -> s1.length() - s2.length();

        // Use sort() to sort the words by their length
        words.sort(lengthComparator);

        System.out.println(words);
    }
}

Outputs:

[rat, cat, mouse, elephant]

In this case, the Comparator is a lambda expression that computes the difference in length between two strings. The List.sort() method uses this Comparator to determine the ordering of the strings in the list.

How do I use List.replaceAll() method?

The List.replaceAll() method was introduced in Java 8. This method replaces each element of the list with the result of applying the operator to that element. The operator or function you pass to replaceAll() should be a UnaryOperator.

Here is a simple example:

package org.kodejava.util;

import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;

public class ListReplaceAllExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);

        // Define an UnaryOperator to square each number
        UnaryOperator<Integer> square = n -> n * n;

        // Use replaceAll() method to square each number in the list
        numbers.replaceAll(square);

        System.out.println(numbers);
    }
}

Outputs:

[1, 4, 9, 16, 25]

In this example, the UnaryOperator square squares each element. The List.replaceAll() method applies this operator to all elements in the list.

Note that replaceAll() modifies the original list and does not return a new list. Please also be aware that this operation is in-place and hence modifies the original List. If you want to keep the original List unchanged, create a new List and add elements to it after applying the function.

The primary purpose of the List.replaceAll() method in Java is to perform an in-place transformation of all elements within a list based on a given unary function or operation.

A Unary function or operation is one that takes a single input and produces a result. In the context of replaceAll(), the unary operation is typically provided as a lambda expression or method reference which is applied to each element in the list in turn.

If successful, replaceAll() modifies the list such that each original element has been replaced by the result of applying the provided unary operation to that element. This operation is performed on the original list, and no new list is created, making it an efficient option for transforming large lists.

Here is an example which doubles each integer in a list:

package org.kodejava.util;

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

public class ListReplaceAllSecondExample {
    public static void main(String[] args) {
        List<Integer> ints = new ArrayList<>();

        ints.add(1);
        ints.add(2);
        ints.add(3);

        // Double every integer in the List
        ints.replaceAll(n -> n * 2);

        System.out.println(ints); 
    }
}

Outputs:

[2, 4, 6]

In conclusion, List.replaceAll() provides a convenient and efficient way to modify all elements in a list according to a specified operation or function. It’s especially useful when using the Streams API and functional programming techniques introduced in Java 8.

How do I use List.of() factory method to create a list object?

In Java, you can use the List.of() factory method to create an unmodifiable List consisting of specified elements. This method is available from Java 9 onwards.

Here is a simple example:

package org.kodejava.util;

import java.util.List;

public class ListOfExample {
    public static void main(String[] args) {
        List<String> names = List.of("Rosa", "John", "Mary", "Alice");

        for (String name : names) {
            System.out.println(name);
        }

        names.add("Bob"); // throws java.lang.UnsupportedOperationException
    }
}

In the code above, we have created a list of names including “Rosa”, “John”, “Mary”, and “Alice”. This newly created list is unmodifiable, so attempting to add, update, or remove elements from it will throw an UnsupportedOperationException.

There are several overloaded versions of the List.of() method that each accept different numbers of arguments. The versions range from no argument (which creates an empty list) to 10 explicit arguments of type E. Here’s an example:

List<String> a = List.of(); // An empty list
List<String> b = List.of("One"); // A list with one element
List<String> c = List.of("One", "Two"); // A list with two elements
// ...
List<String> j = List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"); // A list with ten elements

However, if we need to create a list with more than 10 elements, we have another overloaded version of List.of() method which accepts an array or varargs.

List<String> list = List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven");

Remember that these lists are unmodifiable. That means, if you try to modify the list (add, update, or remove elements) after they have been created, an UnsupportedOperationException will be thrown. Also, List.of() doesn’t allow null elements. If you pass null, it will throw UnsupportedOperationException.

How do I create an ordered list in iText 8?

Creating an ordered list in iText 8 involves creating a List object and adding ListItem objects to it, similarly to creating an unordered list.

For automatic numbering or bullets in a list, you’ll have to use ListNumberingType with the appropriate configuration. For example, ListNumberingType.DECIMAL for Arabic number (1, 2, 3, etc.) and ListNumberingType.ENGLISH_LOWER for English lower case alphabet (a, b, c, etc.).

Here’s an example:

package org.kodejava.itext;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.ListItem;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.properties.ListNumberingType;

public class OrderedListExample {
    public static void main(String[] args) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter("output.pdf"));
        try (Document doc = new Document(pdfDoc)) {
            // Create a List object and set numbering type
            List list = new List(ListNumberingType.DECIMAL);

            // Add ListItems
            list.add(new ListItem("First item"));
            list.add(new ListItem("Second item"));
            list.add(new ListItem("Third item"));
            list.add(new ListItem("Fourth item"));

            // Add the list to our document
            doc.add(list);
        }
    }
}

In this example, we’re passing ListNumberingType.DECIMAL to the List constructor. This will number our list items as follows: “1.”, “2.”, “3.”, etc.

Other options you’ll find in the ListNumberingType enum are:

  • DECIMAL_LEADING_ZERO
  • ENGLISH_LOWER
  • ENGLISH_UPPER
  • ROMAN_LOWER
  • ROMAN_UPPER
  • GREEK_LOWER
  • GREEK_UPPER
  • ZAPF_DINGBATS_1
  • ZAPF_DINGBATS_2
  • ZAPF_DINGBATS_3
  • ZAPF_DINGBATS_4

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.4</version>
    <type>pom</type>
</dependency>

Maven Central

How do I create an unordered list in iText 8?

Creating an unordered list in iText 8 involves creating a List object and adding ListItem objects to it.

Here is an example of how you can do this:

package org.kodejava.itext;

import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.ListItem;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;

public class UnorderedListExample {
    public static void main(String[] args) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter("output.pdf"));
        try (Document doc = new Document(pdfDoc)) {
            // Create a List object
            List list = new List();
            list.setListSymbol("\u2022 ");

            // Add ListItems
            list.add(new ListItem("First item"));
            list.add(new ListItem("Second item"));
            list.add(new ListItem("Third item"));
            list.add(new ListItem("Fourth item"));

            // Add the list to our document
            doc.add(list);
        }
    }
}

In this code:

  • A PdfDocument object is created to write to a PDF file named “output.pdf”.
  • A Document object is created, which represents an actual PDF document.
  • A List object is created, representing the unordered list.
  • ListItem objects representing individual list items are added to the List.
  • Finally, the List is added to the Document, and the Document is automatically closed by the try-with-resource block, and flush any remaining content to the PDF.

You may put different things in your ListItem objects, and nest other List objects within them, if you wish.

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.4</version>
    <type>pom</type>
</dependency>

Maven Central