How do I use Set.of() factory method to create a set object?

As with List.of(), in Java 9, the Set.of() factory method can be used to create an unmodifiable set of specified elements.

Here is a simple example:

package org.kodejava.util;

import java.util.Set;

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

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

Output:

John
Rosa
Alice
Mary

In this example, the Set.of("Rosa", "John", "Mary", "Alice") statement creates an unmodifiable set of strings containing “Rosa”, “John”, “Mary”, and “Alice”. The resulting set is unmodifiable, so attempting to add, update, or remove elements from it will throw an UnsupportedOperationException.

If you try to create a Set by providing a duplicate elements, an IllegalArgumentException will be thrown. A Set is a type of collection container that cannot have duplicate values in it.

Note that the Set.of() method doesn’t accept null values. If you try to insert a null value, it will throw a NullPointerException. If you add a null value using the add() method UnsupportedOperationException will be thrown.

Set.of() is overloaded similarly to List.of(), allowing you to create a set with varying numbers of elements. The below examples demonstrate the use of Set.of() with different numbers of arguments:

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

If you need to create a set with more than 10 elements, Set.of() offers an overloaded version that accepts an array or varargs:

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

Remember that sets created with Set.of() are unmodifiable. Attempting to add, remove or change an element in these sets after their creation causes an UnsupportedOperationException.

Also, Set.of() doesn’t allow duplicate or null elements. If you pass duplicate or null values, it will throw IllegalArgumentException and NullPointerException respectively.

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.2</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.2</version>
    <type>pom</type>
</dependency>

Maven Central

How do I set the indentation of a Paragraph object in iText 8?

In iText 8, indentation of a Paragraph can be controlled using the setMarginLeft() and setMarginRight() method of the BlockElement class which is the super class of Paragraph.

Here is an example of how to indent a paragraph:

package org.kodejava.itext;

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

public class ParagraphIndentation {
    public static void main(String[] args) throws Exception {
        PdfWriter writer = new PdfWriter("indentation.pdf");
        PdfDocument pdf = new PdfDocument(writer);

        try (Document document = new Document(pdf)) {
            String first = """
                    Lorem ipsum dolor sit amet, consectetur adipisicing elit, \
                    sed do eiusmod tempor incididunt ut labore et dolore magna \
                    aliqua. Ut enim ad minim veniam, quis nostrud exercitation \
                    ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                    """;
            String second = """
                    Duis aute irure dolor in  reprehenderit in voluptate velit \
                    esse cillum dolore eu fugiat nulla pariatur. Excepteur sint \
                    occaecat cupidatat non proident, sunt in culpa qui officia \
                    deserunt mollit anim id est laborum.
                    """;

            Paragraph firstParagraph = new Paragraph(first);
            firstParagraph.setFirstLineIndent(60);
            firstParagraph.setMarginLeft(50);
            firstParagraph.setMarginRight(50);
            document.add(firstParagraph);

            Paragraph secondParagraph = new Paragraph(second);
            secondParagraph.setFirstLineIndent(60);
            secondParagraph.setMarginLeft(50);
            secondParagraph.setMarginRight(50);
            document.add(secondParagraph);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, setMarginLeft() and setMarginRight() methods are used to set the left and right indentation of the paragraph. These methods accept a float value as the parameter for setting the left and right indentation respectively.

The setFirstLineIndent() method in the Paragraph class sets the indentation of the first line of a Paragraph in points. This option is commonly used in document formatting where the first line of a paragraph is typically indented more than the rest of the text in the paragraph.

For example, if you set paragraph.setFirstLineIndent(60);, the first line of the text in that paragraph would be indented 60 points from the left margin.

The generated PDF document looks like this:

Paragraph Indentation

Maven Dependencies

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

Maven Central