How do I convert arrays to lists and vice versa in Kotlin?

In Kotlin, you can convert arrays to lists and lists to arrays using standard library functions.

Array to List

Use toList():

val array = arrayOf("a", "b", "c")

val list: List<String> = array.toList()

println(list) // [a, b, c]

If you want a mutable list, use toMutableList():

val array = arrayOf("a", "b", "c")

val mutableList: MutableList<String> = array.toMutableList()

mutableList.add("d")

println(mutableList) // [a, b, c, d]

List to Array

Use toTypedArray():

val list = listOf("a", "b", "c")

val array: Array<String> = list.toTypedArray()

println(array.contentToString()) // [a, b, c]

Primitive Arrays

Kotlin has special primitive array types like IntArray, DoubleArray, and BooleanArray.

IntArray to List

val intArray = intArrayOf(1, 2, 3)

val list: List<Int> = intArray.toList()

println(list) // [1, 2, 3]

List<Int> to IntArray

Use toIntArray():

val list = listOf(1, 2, 3)

val intArray: IntArray = list.toIntArray()

println(intArray.contentToString()) // [1, 2, 3]

Other primitive conversions work similarly:

val doubles: List<Double> = listOf(1.1, 2.2, 3.3)
val doubleArray: DoubleArray = doubles.toDoubleArray()

val booleans: List<Boolean> = listOf(true, false)
val booleanArray: BooleanArray = booleans.toBooleanArray()

Important Note: asList()

For object arrays, you can also use asList():

val array = arrayOf("a", "b", "c")

val list = array.asList()

The difference is:

val array = arrayOf("a", "b", "c")

val copiedList = array.toList()
val backedList = array.asList()
  • toList() creates a new list copy.
  • asList() returns a list backed by the original array.

Example:

val array = arrayOf("a", "b", "c")
val list = array.asList()

array[0] = "z"

println(list) // [z, b, c]

So in most cases, use:

array.toList()
list.toTypedArray()

And for primitive types:

intArray.toList()
list.toIntArray()

How do I sort a list of values in Kotlin?

In Kotlin, you usually sort a list with sorted():

val numbers = listOf(5, 2, 8, 1)

val sortedNumbers = numbers.sorted()

println(sortedNumbers) // [1, 2, 5, 8]

sorted() returns a new sorted list and does not change the original list.

For descending order, use sortedDescending():

val numbers = listOf(5, 2, 8, 1)

val sortedDescending = numbers.sortedDescending()

println(sortedDescending) // [8, 5, 2, 1]

For objects, sort by a property with sortedBy():

data class Person(val name: String, val age: Int)

val people = listOf(
    Person("Alice", 30),
    Person("Bob", 25),
    Person("Charlie", 35)
)

val sortedByAge = people.sortedBy { it.age }

println(sortedByAge)
// [Person(name=Bob, age=25), Person(name=Alice, age=30), Person(name=Charlie, age=35)]

If you have a mutable list and want to sort it in place, use sort():

val numbers = mutableListOf(5, 2, 8, 1)

numbers.sort()

println(numbers) // [1, 2, 5, 8]

Quick summary:

  • sorted() — returns a new ascending list
  • sortedDescending() — returns a new descending list
  • sortedBy { ... } — sorts by a property
  • sort() — sorts a mutable list in place

How do I create and use lists, sets, and maps in Kotlin?

In Kotlin, the main collection types are List, Set, and Map.

Kotlin provides both read-only and mutable versions:

Collection Read-only Mutable
List List<T> MutableList<T>
Set Set<T> MutableSet<T>
Map Map<K, V> MutableMap<K, V>

Lists

A list is an ordered collection. It can contain duplicate elements.

Read-only list

val numbers = listOf(1, 2, 3, 3)

println(numbers[0])        // 1
println(numbers.size)      // 4
println(numbers.contains(2)) // true

You cannot add or remove items from a read-only List.

val names = listOf("Alice", "Bob", "Charlie")

for (name in names) {
    println(name)
}

Mutable list

val names = mutableListOf("Alice", "Bob")

names.add("Charlie")
names.remove("Alice")
names[0] = "Bobby"

println(names) // [Bobby, Charlie]

You can also create an empty mutable list:

val items = mutableListOf<String>()

items.add("Book")
items.add("Pen")

println(items) // [Book, Pen]

Sets

A set is a collection of unique elements. It does not allow duplicates.

Read-only set

val numbers = setOf(1, 2, 3, 3)

println(numbers) // [1, 2, 3]
println(2 in numbers) // true

Mutable set

val fruits = mutableSetOf("Apple", "Banana")

fruits.add("Orange")
fruits.add("Apple") // Duplicate, ignored
fruits.remove("Banana")

println(fruits) // [Apple, Orange]

Empty mutable set:

val ids = mutableSetOf<Int>()

ids.add(101)
ids.add(102)

println(ids) // [101, 102]

Maps

A map stores key-value pairs. Each key is unique.

Read-only map

val ages = mapOf(
    "Alice" to 25,
    "Bob" to 30,
    "Charlie" to 35
)

println(ages["Alice"]) // 25
println(ages["Unknown"]) // null
println(ages.containsKey("Bob")) // true
println(ages.containsValue(30)) // true

Mutable map

val scores = mutableMapOf(
    "Alice" to 90,
    "Bob" to 85
)

scores["Charlie"] = 95
scores["Alice"] = 100
scores.remove("Bob")

println(scores) // {Alice=100, Charlie=95}

Empty mutable map:

val phoneBook = mutableMapOf<String, String>()

phoneBook["Alice"] = "123-456"
phoneBook["Bob"] = "987-654"

println(phoneBook["Alice"]) // 123-456

Common operations

Iterating over a list or set

val colors = listOf("Red", "Green", "Blue")

for (color in colors) {
    println(color)
}

Iterating over a map

val ages = mapOf(
    "Alice" to 25,
    "Bob" to 30
)

for ((name, age) in ages) {
    println("$name is $age years old")
}

Filtering

val numbers = listOf(1, 2, 3, 4, 5, 6)

val evenNumbers = numbers.filter { it % 2 == 0 }

println(evenNumbers) // [2, 4, 6]

Mapping values

val names = listOf("alice", "bob", "charlie")

val uppercaseNames = names.map { it.uppercase() }

println(uppercaseNames) // [ALICE, BOB, CHARLIE]

Sorting

val numbers = listOf(5, 2, 8, 1)

val sorted = numbers.sorted()

println(sorted) // [1, 2, 5, 8]

Checking contents

val names = listOf("Alice", "Bob")

println("Alice" in names) // true
println("Charlie" !in names) // true

Choosing between them

Use a List when:

  • Order matters
  • Duplicates are allowed
  • You access elements by index
val tasks = listOf("Write", "Test", "Deploy")

Use a Set when:

  • Values must be unique
  • You mainly check whether something exists
val uniqueTags = setOf("kotlin", "backend", "api")

Use a Map when:

  • You need key-value lookup
  • Each key maps to one value
val userRoles = mapOf(
    1 to "Admin",
    2 to "Editor",
    3 to "Viewer"
)

Quick summary

val readOnlyList = listOf("A", "B", "C")
val mutableList = mutableListOf("A", "B")
mutableList.add("C")

val readOnlySet = setOf("A", "B", "A") // [A, B]
val mutableSet = mutableSetOf("A", "B")
mutableSet.add("C")

val readOnlyMap = mapOf("Alice" to 25, "Bob" to 30)
val mutableMap = mutableMapOf("Alice" to 25)
mutableMap["Bob"] = 30

In short:

  • listOf() creates a read-only list
  • mutableListOf() creates a mutable list
  • setOf() creates a read-only set
  • mutableSetOf() creates a mutable set
  • mapOf() creates a read-only map
  • mutableMapOf() creates a mutable map

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

How do I use Collectors.toList() method?

The Collectors.toList() method is a convenient method in the java.util.stream.Collectors class that provides a Collector to accumulate input elements into a new List.

Here is a simple example of how to use Collectors.toList():

package org.kodejava.stream;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CollectorsToList {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        List<Integer> evenNumbers = numbers.stream()
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList());

        System.out.println(evenNumbers);
    }
}

Output:

[2, 4, 6, 8]

In this example, we create a stream of numbers and filter it to only include the even numbers. Then we collect the output into a List using Collectors.toList(). The result is a List<Integer> that only includes the even numbers.

Remember that collect is a terminal operation (meaning it triggers the processing of the data) and it returns a collection or other desired result type. In case of Collectors.toList(), the result is a List.

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]