How do I loop through the entries of a HashMap in Java?

You can use entrySet() with an enhanced for loop to read each key-value pair in a HashMap.

In this example, you will store product names and their quantities, then print each entry.

Source code

Save the following code as HashMapLoopExample.java:

import java.util.HashMap;
import java.util.Map;

public class HashMapLoopExample {
    void main() {
        Map<String, Integer> inventory = new HashMap<>();

        inventory.put("Notebook", 12);
        inventory.put("Pen", 30);
        inventory.put("Pencil", 20);

        for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
            String product = entry.getKey();
            int quantity = entry.getValue();

            IO.println(product + ": " + quantity);
        }

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

Explanation

A map stores values associated with unique keys. In this example, each product name is a key, and its quantity is the corresponding value:

Map<String, Integer> inventory = new HashMap<>();

The type arguments specify that keys are strings and values are integers. Java generics use reference types, so the value type is Integer rather than int.

Adding entries

Use put() to add a key-value pair:

inventory.put("Notebook", 12);

Java automatically boxes the quantity into an Integer.

If you call put() again with an existing key, the new value replaces the previous value for that key.

Reading entries with entrySet()

The entrySet() method provides a set view of the map’s entries:

inventory.entrySet()

Each entry contains both a key and its associated value. The enhanced for loop reads one entry at a time:

for (Map.Entry<String, Integer> entry : inventory.entrySet()) {

Inside the loop, use getKey() and getValue() to access the pair:

String product = entry.getKey();
int quantity = entry.getValue();

Assigning the Integer value to an int automatically unboxes it. All values in this example are non-null.

Using entrySet() lets you read the key and value together without performing a separate lookup with get().

Counting entries

The size() method returns the number of key-value pairs:

inventory.size()

Here, the result is 3. It counts product entries, not the sum of their quantities.

Run the example

Compile and run the file:

javac HashMapLoopExample.java
java HashMapLoopExample

Example output

Notebook: 12
Pen: 30
Pencil: 20
Total products: 3

A HashMap does not guarantee iteration order, so the product lines may appear in a different order.

Using forEach()

For a shorter alternative, replace the loop with:

inventory.forEach((product, quantity) ->
        IO.println(product + ": " + quantity));

This passes each key and value to the lambda expression. It also follows the map’s iteration order, which remains unspecified for a HashMap.

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.