How do I filter a list using a stream in Java?

You can use the Stream API’s filter() method to select elements that match a condition.

In this example, you will select numbers greater than or equal to 20 from a list and collect them into a new list.

Source code

Save the following code as FilterListExample.java:

import java.util.List;

public class FilterListExample {
    void main() {
        List<Integer> numbers = List.of(5, 20, 12, 35, 8, 40);

        List<Integer> filteredNumbers = numbers.stream()
                .filter(number -> number >= 20)
                .toList();

        IO.println("Original list: " + numbers);
        IO.println("Filtered list: " + filteredNumbers);
    }
}

Explanation

The original list contains six integers:

List<Integer> numbers = List.of(5, 20, 12, 35, 8, 40);

The following pipeline selects the matching values and collects them:

List<Integer> filteredNumbers = numbers.stream()
        .filter(number -> number >= 20)
        .toList();

Each step has a purpose:

Step Purpose
stream() Creates a sequential stream of the list’s elements
filter(...) Keeps elements that match the condition
toList() Collects the selected elements into a list

Defining the condition

The filter() method accepts a predicate: a function that checks an element and returns true or false.

Here, the predicate is a lambda expression:

number -> number >= 20

When the result is true, the number remains in the stream. When it is false, the number is excluded.

For this input, the matching values are 20, 35, and 40.

Collecting the result

filter() is an intermediate operation. It describes the selection but does not process the elements until a terminal operation runs.

In this example, toList() is the terminal operation:

.toList()

It collects the matching elements into an unmodifiable list. Calling add() or remove() on that result would throw an UnsupportedOperationException.

The result preserves the original list’s encounter order. Filtering does not change the original list.

Run the example

Compile and run the file:

javac FilterListExample.java
java FilterListExample

Output

Original list: [5, 20, 12, 35, 8, 40]
Filtered list: [20, 35, 40]

Combining conditions

Use && to require multiple conditions. For example, this filter keeps numbers that are at least 20 and even:

.filter(number -> number >= 20 && number % 2 == 0)

With the same input, the resulting list is:

[20, 40]

If no elements match the condition, toList() returns an empty list.

How do I sort a list of objects by a field in Java?

You can use Comparator.comparing() to sort objects by a field exposed through an accessor method.

In this example, you will sort a list of books alphabetically by title.

Source code

Save the following code as SortObjectsExample.java:

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

public class SortObjectsExample {
    void main() {
        List<Book> books = new ArrayList<>(List.of(
                new Book("Learning Java", "Alice"),
                new Book("Exploring Java", "Bob"),
                new Book("Building Java Apps", "Carol")
        ));

        books.sort(Comparator.comparing(Book::title));

        for (Book book : books) {
            IO.println(book.title() + " by " + book.author());
        }
    }
}

record Book(String title, String author) {
}

Explanation

The Book record stores a title and an author:

record Book(String title, String author) {
}

Java provides the accessor methods title() and author() automatically.

The example creates an ArrayList containing three books. This list supports sorting, unlike the unmodifiable list returned directly by List.of().

Creating a comparator

The following expression creates a comparator that compares books by title:

Comparator.comparing(Book::title)

The method reference Book::title tells the comparator which value to extract from each book.

Because the extracted values are strings, the comparator uses their natural ordering. For these titles, that produces alphabetical order. String natural ordering is case-sensitive.

Sorting the list

Pass the comparator to sort():

books.sort(Comparator.comparing(Book::title));

This rearranges the elements in the existing list. It does not create a separate sorted list.

The loop then prints the books in their new order:

for (Book book : books) {
    IO.println(book.title() + " by " + book.author());
}

Run the example

Compile and run the file:

javac SortObjectsExample.java
java SortObjectsExample

Output

Building Java Apps by Carol
Exploring Java by Bob
Learning Java by Alice

Reversing the order

To sort titles in descending order, reverse the comparator:

books.sort(Comparator.comparing(Book::title).reversed());

Comparing another field when titles match

Use thenComparing() to compare authors when two books have equal titles:

books.sort(
        Comparator.comparing(Book::title)
                .thenComparing(Book::author)
);

This sorts by title first, then by author for books with matching titles.

How do I get the first and last elements of a List in Java?

You can use getFirst() and getLast() to read the first and last elements of a list without calculating their indexes.

In this example, you will read the first and last programming language names from a list.

Source code

Save the following code as FirstLastListExample.java:

import java.util.List;

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

        if (languages.isEmpty()) {
            IO.println("The list is empty.");
            return;
        }

        String firstLanguage = languages.getFirst();
        String lastLanguage = languages.getLast();

        IO.println("Languages: " + languages);
        IO.println("First language: " + firstLanguage);
        IO.println("Last language: " + lastLanguage);
    }
}

Explanation

The example creates a list containing three strings:

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

A List maintains its elements in a defined order. Here, "Java" is the first element and "Kotlin" is the last.

Checking for an empty list

Before reading either element, the program checks whether the list is empty:

if (languages.isEmpty()) {
    IO.println("The list is empty.");
    return;
}

Both getFirst() and getLast() throw a NoSuchElementException when called on an empty list.

The return statement ends the method before either call can happen.

Reading the first element

Use getFirst() to retrieve the element at the beginning:

String firstLanguage = languages.getFirst();

For a nonempty list, this returns the same element as get(0).

Reading the last element

Use getLast() to retrieve the element at the end:

String lastLanguage = languages.getLast();

For a nonempty list, this returns the same element as:

languages.get(languages.size() - 1)

The named methods make the intent clear without requiring index calculations. Neither method removes an element or changes the list.

Run the example

Compile and run the file:

javac FirstLastListExample.java
java FirstLastListExample

Output

Languages: [Java, Python, Kotlin]
First language: Java
Last language: Kotlin

If you replace the list declaration with an empty list:

List<String> languages = List.of();

The output becomes:

The list is empty.

For a list containing only one element, getFirst() and getLast() return that same element.

How do I keep a recent files list with SequencedMap in Java 21?

A recent files menu should move a reopened file to the top instead of showing it twice. Once the menu is full, opening a new file should remove the oldest entry. In Java 21, a LinkedHashMap can do both through the SequencedMap interface. See the Java 21 SequencedMap API.

1. Move a reopened file to the newest position

Use a LinkedHashMap to store each file name and its path. The example keeps the oldest entry first and the newest entry last.

On a default LinkedHashMap, calling put() for an existing key changes its value but leaves it in the same position. Calling putLast() also moves the entry to the end. That means reopening notes.txt makes it the newest entry without adding a duplicate. See the Java 21 LinkedHashMap API.

2. Remove the oldest entry when the list is full

After recording a file, check the map’s size. If it exceeds the limit, call pollFirstEntry() to remove and return the oldest entry. Use reversed() when displaying the menu so the newest entry appears first.

3. Run the complete example

Save this code as RecentFilesExample.java. The paths are sample strings; the program does not open any files.

import java.util.LinkedHashMap;
import java.util.SequencedMap;

public class RecentFilesExample {
    private static final int LIMIT = 3;

    public static void main(String[] args) {
        SequencedMap<String, String> recent = new LinkedHashMap<>();

        remember(recent, "notes.txt", "/work/notes.txt");
        remember(recent, "plan.txt", "/work/plan.txt");
        remember(recent, "ideas.txt", "/work/ideas.txt");
        remember(recent, "notes.txt", "/work/notes.txt");

        System.out.println("After reopening: " + recent.sequencedKeySet());

        var removed = remember(recent, "draft.txt", "/work/draft.txt");
        System.out.println("Removed: " + removed);
        System.out.println("Newest first: " + recent.reversed().sequencedKeySet());
    }

    private static String remember(SequencedMap<String, String> recent,
                                   String name, String path) {
        recent.putLast(name, path);
        if (recent.size() > LIMIT) {
            return recent.pollFirstEntry().getKey();
        }
        return null;
    }
}

Compile and run it from the directory containing the file:

javac --release 21 RecentFilesExample.java
java RecentFilesExample

Output:

After reopening: [plan.txt, ideas.txt, notes.txt]
Removed: plan.txt
Newest first: [draft.txt, notes.txt, ideas.txt]

Reopening notes.txt makes plan.txt the oldest entry. Adding draft.txt takes the map over its three-file limit, so plan.txt is removed.

Best practices

  • Use a full path or another stable identifier as the key in a real app. Two folders can contain files with the same name.
  • Update the list after a file opens successfully so failed attempts do not appear in the menu.
  • Treat reversed() as a live view. If you need a list that stays the same when the map changes, take a snapshot with List.copyOf(recent.reversed().sequencedKeySet()).

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.