How do I remove duplicate values using a HashSet in Java?

A HashSet stores unique elements. You can use it to remove duplicate values from a collection by passing that collection to its constructor.

In this example, you will remove duplicate programming language names from a list.

Source code

Save the following code as RemoveDuplicatesExample.java:

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicatesExample {
    void main() {
        List<String> languages = List.of(
                "Java", "Python", "Java", "Kotlin", "Python");

        Set<String> uniqueLanguages = new HashSet<>(languages);

        IO.println("Original list: " + languages);
        IO.println("Original count: " + languages.size());
        IO.println("Unique count: " + uniqueLanguages.size());

        IO.println("Unique languages:");
        uniqueLanguages.stream()
                .sorted()
                .forEach(IO::println);
    }
}

Explanation

The original list contains five elements, including repeated values:

List<String> languages = List.of(
        "Java", "Python", "Java", "Kotlin", "Python");

Both "Java" and "Python" appear twice.

Creating a set from the list

The following statement copies the list’s elements into a HashSet:

Set<String> uniqueLanguages = new HashSet<>(languages);

A set does not retain duplicate elements, so the resulting set contains three language names.

The original list remains unchanged.

The variable uses the interface type Set<String>, while HashSet provides the implementation.

How duplicates are identified

HashSet uses hashCode() and equals() to identify duplicate elements.

For strings, equality depends on their text and is case-sensitive. For example, "Java" and "java" are different values and would both remain in the set.

When storing objects from your own classes, implement equals() and hashCode() consistently so the set can recognize logically equal objects.

Displaying the unique values

A HashSet does not guarantee iteration order. The example sorts the elements before printing them to produce predictable output:

uniqueLanguages.stream()
        .sorted()
        .forEach(IO::println);

stream() creates a stream of the set’s elements. sorted() arranges the strings in their natural order, and forEach() prints each one.

Sorting the stream does not change the set.

Run the example

Compile and run the file:

javac RemoveDuplicatesExample.java
java RemoveDuplicatesExample

Output

Original list: [Java, Python, Java, Kotlin, Python]
Original count: 5
Unique count: 3
Unique languages:
Java
Kotlin
Python

Preserving insertion order

If you want to remove duplicates while preserving the order in which values first appeared, use a LinkedHashSet:

Set<String> uniqueLanguages = new LinkedHashSet<>(languages);

Import java.util.LinkedHashSet to use it. Iterating over this set produces Java, Python, and Kotlin, in that order.

How do I add and remove items from an ArrayList in Java?

An ArrayList stores elements in order and can grow or shrink as you add or remove items.

In this example, you will create a list of programming languages, add elements, and remove them by value and by index.

Source code

Save the following code as ArrayListExample.java:

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

public class ArrayListExample {
    void main() {
        ArrayList<String> languages = new ArrayList<>(
                List.of("Java", "Python"));

        IO.println("Initial list: " + languages);

        languages.add("JavaScript");
        IO.println("After adding JavaScript: " + languages);

        languages.add(1, "Kotlin");
        IO.println("After inserting Kotlin: " + languages);

        boolean removed = languages.remove("Python");
        IO.println("Python removed: " + removed);
        IO.println("After removing Python: " + languages);

        String removedLanguage = languages.remove(0);
        IO.println("Removed at index 0: " + removedLanguage);
        IO.println("Final list: " + languages);

        IO.println("Total languages: " + languages.size());
    }
}

Explanation

The following statement creates a mutable list containing two strings:

ArrayList<String> languages = new ArrayList<>(List.of("Java", "Python"));

List.of() creates an unmodifiable list. Passing it to the ArrayList constructor copies its elements into a new list that supports adding and removing items.

The type argument <String> restricts this list to strings. The diamond operator <> lets the compiler infer the constructor’s type argument.

Adding an item

Use add(element) to append an item to the end:

languages.add("JavaScript");

The list becomes:

[Java, Python, JavaScript]

To insert an item at a specific position, use add(index, element):

languages.add(1, "Kotlin");

Indexes start at zero. This inserts "Kotlin" at the second position and shifts the following elements to the right.

Removing an item by value

Use remove(Object) to remove the first matching item:

boolean removed = languages.remove("Python");

This method returns true if an item was removed, or false if no matching item was found.

If the list contains duplicates, only the first matching occurrence is removed.

Removing an item by index

Use remove(int) to remove an item at a specific position:

String removedLanguage = languages.remove(0);

This removes the first item and returns it. The remaining elements shift to the left.

The index must refer to an existing element. Otherwise, the method throws an IndexOutOfBoundsException.

Getting the number of items

Use size() to read the number of elements:

languages.size()

Unlike an array’s length field, an ArrayList uses a method with parentheses.

Run the example

Compile and run the file:

javac ArrayListExample.java
java ArrayListExample

Output

Initial list: [Java, Python]
After adding JavaScript: [Java, Python, JavaScript]
After inserting Kotlin: [Java, Kotlin, Python, JavaScript]
Python removed: true
After removing Python: [Java, Kotlin, JavaScript]
Removed at index 0: Java
Final list: [Kotlin, JavaScript]
Total languages: 2

Removing integers by value

For an ArrayList<Integer>, passing an int to remove() selects the index-based overload:

numbers.remove(1);

This removes the element at index 1. To remove the value 1, explicitly pass an Integer:

numbers.remove(Integer.valueOf(1));

How do I convert byte arrays to hexadecimal and back in Java 17?

When you inspect binary data, a hexadecimal string can be easier to read than a list of decimal byte values. You might use it when troubleshooting a file format or checking a message exchanged between applications.

This tutorial shows a complete conversion in both directions, including readable formatting and invalid input handling.

1. Choose a hexadecimal format

Java 17 introduced java.util.HexFormat as a standard API. No preview or incubator flags are needed.

Use HexFormat.of() for lowercase output without separators. For uppercase output with colons between bytes, use:

HexFormat readable =
        HexFormat.ofDelimiter(":").withUpperCase();

Each byte becomes two hexadecimal digits. These options are documented in the Java 17 HexFormat API.

2. Create the complete example

Save the following as HexFormatExample.java:

import java.util.Arrays;
import java.util.HexFormat;

public class HexFormatExample {
    public static void main(String[] args) {
        byte[] packet = {
                0, 15, 16, 127, (byte) 128, (byte) 255
        };

        HexFormat plain = HexFormat.of();
        HexFormat readable =
                HexFormat.ofDelimiter(":").withUpperCase();

        System.out.println(
                "Compact: " + plain.formatHex(packet));

        String formatted = readable.formatHex(packet);
        System.out.println("Readable: " + formatted);

        byte[] restored = readable.parseHex(formatted);
        System.out.println(
                "Same bytes: " + Arrays.equals(packet, restored));
        System.out.println(
                "Java bytes: " + Arrays.toString(restored));

        try {
            readable.parseHex("00:GG");
        } catch (IllegalArgumentException exception) {
            System.out.println(
                    "Invalid input: expected hexadecimal byte pairs");
        }
    }
}

The program first creates sample data. It then prints two representations, parses the colon-separated version, and checks whether the recovered bytes match the original.

3. Compile and run

Open a terminal in the directory containing the file:

javac --release 17 HexFormatExample.java
java HexFormatExample

Output:

Compact: 000f107f80ff
Readable: 00:0F:10:7F:80:FF
Same bytes: true
Java bytes: [0, 15, 16, 127, -128, -1]
Invalid input: expected hexadecimal byte pairs

4. Understand the result

The two formatted strings represent identical data. Java’s signed byte representation explains the negative decimal values in the recovered array: the bit patterns 80 and FF correspond to -128 and -1.

Arrays.equals() confirms that the conversion preserved the bytes.

Parsing must use the expected delimiters. Invalid digits, such as GG, cause IllegalArgumentException; hexadecimal digit letters themselves are case-insensitive. See HexFormat.parseHex().

Best practices

  • Define the expected representation when exchanging data with another application.
  • Use a matching formatter for encoding and decoding.
  • Keep the original bytes when your next operation requires binary data.
  • Handle invalid external input at the point where it enters your application.
  • Remember that hexadecimal encoding makes data readable; it does not encrypt it.

Summary

Use formatHex() to turn bytes into hexadecimal text and parseHex() to recover them. A short round-trip example helps verify your chosen representation before integrating it into a larger application.

How do I protect a List inside a Java record?

A record is a convenient way to represent data, but a record containing a mutable list can still change unexpectedly. In this tutorial, you will protect a reading list from changes made through other references.

Records became a final language feature in Java 16. This tutorial uses Java 17 as its baseline and requires no preview or incubator flags. See Java’s language changes by release.

1. Understand the problem

Consider this record:

record ReadingList(String title, List<String> books) {
}

Java generates its constructor and accessors. However, the generated constructor stores the supplied list reference. A caller holding that list can change its contents afterward.

A final field prevents reassignment of the reference; it does not freeze the referenced object. Java’s record documentation explains the fields and methods generated for records.

2. Protect the list during construction

Use a compact constructor to replace the incoming list with an unmodifiable snapshot:

ReadingList {
    books = List.copyOf(books);
}

Assign to the constructor parameter, books. Java assigns the resulting value to the component field after the constructor body completes.

List.copyOf() preserves element order and prevents later changes to the original list from affecting the result. It rejects null collections and null elements. See the Java 17 List API.

3. Create the complete example

Save this code as RecordListExample.java:

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

public class RecordListExample {
    record ReadingList(String title, List<String> books) {
        ReadingList {
            if (title == null || title.isBlank()) {
                throw new IllegalArgumentException(
                        "Title must not be blank");
            }
            books = List.copyOf(books);
        }
    }

    public static void main(String[] args) {
        List<String> original =
                new ArrayList<>(List.of("Java Basics"));

        ReadingList readingList =
                new ReadingList("Weekend", original);

        original.add("Advanced Java");

        System.out.println("Original: " + original);
        System.out.println("Record: " + readingList.books());

        try {
            readingList.books().add("Another Book");
        } catch (UnsupportedOperationException exception) {
            System.out.println("Record list cannot be modified");
        }
    }
}

The example checks two paths: modifying the original list and attempting a modification through the record’s accessor.

4. Compile and run

Open a terminal in the directory containing the file:

javac --release 17 RecordListExample.java
java RecordListExample

Output:

Original: [Java Basics, Advanced Java]
Record: [Java Basics]
Record list cannot be modified

The original list accepts another book. The record keeps its initial contents, and its returned list rejects additions.

5. Know the limit: elements are not copied

This approach protects the list structure. It does not create separate copies of its elements.

Here, the elements are strings, which are immutable. If the list contained mutable Book objects, callers could still change those objects. Use immutable element types or copy mutable elements when your data model requires deeper protection.

Best practices

  • Copy incoming collections at construction boundaries.
  • Document your null policy; this example rejects null lists and null elements.
  • Prefer immutable element types for value objects.
  • Avoid unnecessary copying in the accessor when the stored list is already protected.
  • Treat the caught exception as a demonstration; normal application code should avoid attempting unsupported modifications.

Summary

A record does not automatically make a referenced list immutable. Using List.copyOf() in its compact constructor protects the list against external structural changes while keeping the record concise.

How do I create custom thread factories?

Creating a custom thread factory in Java is a powerful way to manage how threads are initialized. Instead of using the default factory, you can customize thread names (vital for debugging!), set priority levels, or even create daemon threads.

To do this, you need to implement the java.util.concurrent.ThreadFactory interface.

1. Implement the ThreadFactory Interface

The interface has a single method: newThread(Runnable r). Here is a clean, reusable example:

package org.kodejava.util.concurrent;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomThreadFactory implements ThreadFactory {
    private final String namePrefix;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final boolean daemon;

    public CustomThreadFactory(String poolName, boolean daemon) {
        this.namePrefix = poolName + "-worker-";
        this.daemon = daemon;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
        t.setDaemon(daemon);
        t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}

2. Use the Factory with an ExecutorService

Once you’ve defined your factory, you can pass it to any ThreadPoolExecutor or static Executors factory method. This ensures every thread created by that pool follows your rules.

package org.kodejava.util.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadFactoryDemo {
    public static void main(String[] args) {
        // Create the factory
        CustomThreadFactory factory = new CustomThreadFactory("OrderProcessor", false);

        // Pass it to a Fixed Thread Pool
        ExecutorService executor = Executors.newFixedThreadPool(3, factory);

        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                System.out.println("Running task in: " + Thread.currentThread().getName());
            });
        }

        executor.shutdown();
    }
}

Why use a custom factory?

  • Identifiability: In thread dumps or logs, seeing OrderProcessor-worker-1 is much more helpful than pool-1-thread-1.
  • Security & Cleanup: You can set setDaemon(true) for background cleanup tasks so they don’t prevent the JVM from shutting down.
  • Context: You can use the factory to inject ThreadLocal variables or set a custom UncaughtExceptionHandler for all threads in a pool.