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 build a string using StringBuilder in Java?

You can use StringBuilder to build text by appending values to a mutable sequence of characters.

In this example, you will combine a book’s title, author, and publication year into one string.

Source code

Save the following code as StringBuilderExample.java:

public class StringBuilderExample {
    void main() {
        String title = "Learning Java";
        String author = "Alice";
        int year = 2026;

        StringBuilder builder = new StringBuilder();

        builder.append("Title: ")
                .append(title)
                .append(System.lineSeparator())
                .append("Author: ")
                .append(author)
                .append(System.lineSeparator())
                .append("Year: ")
                .append(year);

        String details = builder.toString();

        IO.println(details);
    }
}

Explanation

Strings are immutable, so their contents cannot be changed after creation. A StringBuilder provides a mutable buffer that you can update while building text.

Create an empty builder using its constructor:

StringBuilder builder = new StringBuilder();

StringBuilder belongs to java.lang, so no import is required.

Appending values

The append() method adds a value to the end of the builder:

builder.append("Title: ");
builder.append(title);

These calls produce:

Title: Learning Java

You can append strings, characters, numbers, and other values. For example, the following call appends the text representation of the integer year:

builder.append(year);

Chaining method calls

Each append() call returns the same builder, allowing you to chain calls:

builder.append("Title: ")
        .append(title);

This updates one builder. It does not create a separate builder for each call.

The example uses System.lineSeparator() to insert the platform’s line separator between the book details.

Creating the final string

After building the text, call toString():

String details = builder.toString();

This returns a String containing the builder’s current text. Later changes to the builder do not change that string.

Finally, IO.println(details) prints the result.

Run the example

Compile and run the file:

javac StringBuilderExample.java
java StringBuilderExample

Output

Title: Learning Java
Author: Alice
Year: 2026

Use StringBuilder when you need to build text through repeated updates, especially inside a loop. For a short, fixed expression, string concatenation with + is often easier to read.

How do I split a string into words in Java?

You can use the split() method to divide a string into smaller parts. The method accepts a regular expression that defines where to split and returns an array of strings.

In this example, you will split a sentence into words using whitespace as the separator.

Source code

Save the following code as SplitStringExample.java:

public class SplitStringExample {
    void main() {
        String text = "  Learn Java   one snippet\tat a time.  ";

        if (text.isBlank()) {
            IO.println("The text contains no words.");
            return;
        }

        String[] words = text.strip().split("\\p{javaWhitespace}+");

        for (String word : words) {
            IO.println(word);
        }

        IO.println("Total words: " + words.length);
    }
}

Explanation

The input contains spaces at both ends, multiple spaces between some words, and a tab character:

String text = "  Learn Java   one snippet\tat a time.  ";

The escape sequence \t represents a tab.

Checking for blank text

Before splitting, the program checks whether the text is empty or contains only whitespace:

if (text.isBlank()) {
    IO.println("The text contains no words.");
    return;
}

This avoids treating an empty string as a word. The return statement ends the method when there is no text to process.

Removing surrounding whitespace

The strip() method removes leading and trailing whitespace:

text.strip()

It returns a string without changing the original string, because strings are immutable.

Splitting on whitespace

The following statement splits the cleaned text:

String[] words = text.strip().split("\\p{javaWhitespace}+");

The regular expression has two parts:

Part Meaning
\p{javaWhitespace} Matches whitespace recognized by Character.isWhitespace()
+ Matches one or more consecutive whitespace characters

The backslash is written twice in the Java string literal so the regular expression receives a single backslash.

Using + treats consecutive spaces or tabs as one separator. This prevents empty elements between words when several whitespace characters appear together.

Reading the results

The enhanced for loop prints each element:

for (String word : words) {
    IO.println(word);
}

The array’s length field gives the number of resulting words.

Run the example

Compile and run the file:

javac SplitStringExample.java
java SplitStringExample

Output

Learn
Java
one
snippet
at
a
time.
Total words: 7

This example treats each whitespace-separated token as a word. Punctuation remains attached, so the last token is "time.". For language-aware word boundaries, use a text-processing tool such as BreakIterator.

How do I compare two strings in Java?

Use the equals() method to check whether two strings contain the same text. Use equalsIgnoreCase() when capitalization should not affect the comparison.

In this example, you will compare strings with identical text and strings with different capitalization.

Source code

Save the following code as StringComparisonExample.java:

public class StringComparisonExample {
    void main() {
        String first = "Java";
        String second = new String("Java");
        String third = "java";

        IO.println("Same text: " + first.equals(second));
        IO.println("Same object: " + (first == second));
        IO.println("Same case-sensitive text: " + first.equals(third));
        IO.println("Same text ignoring case: "
                + first.equalsIgnoreCase(third));
    }
}

Explanation

The example creates three string variables:

String first = "Java";
String second = new String("Java");
String third = "java";

The first two strings contain identical text. The third starts with a lowercase letter.

The explicit new String("Java") creates a separate object to demonstrate the difference between comparing text and comparing references. In ordinary code, prefer a string literal when you do not need a separate object.

Comparing text with equals()

The equals() method compares the contents of strings:

first.equals(second)

This returns true because both strings contain "Java".

The comparison is case-sensitive:

first.equals(third)

This returns false because "Java" and "java" have different capitalization.

Comparing references with ==

For strings, the == operator checks whether two references point to the same object:

first == second

This returns false because second refers to a separately created string object, even though the text is identical.

String literals may share an object, so == can sometimes return true for strings containing the same text. Always use equals() when your intention is to compare their contents.

Ignoring capitalization

Use equalsIgnoreCase() when letter case should not affect the result:

first.equalsIgnoreCase(third)

This returns true for "Java" and "java".

Run the example

Compile and run the file:

javac StringComparisonExample.java
java StringComparisonExample

Output

Same text: true
Same object: false
Same case-sensitive text: false
Same text ignoring case: true

Handling null values

Calling equals() on a variable containing null throws a NullPointerException.

When comparing a variable with a known string literal, put the literal first:

"Java".equals(value)

This returns false if value is null.

If either of two variables may be null, use Objects.equals():

Objects.equals(firstValue, secondValue)

Import java.util.Objects to use this method. It returns true when both arguments are null, and otherwise compares their values safely.