Collecting a Stream to an Immutable Collection in Java

Collecting a Stream to an Immutable Collection in Java

In Java, the Stream API introduced in Java 8 provides a powerful way to process collections of data. However, the result of a stream operation is typically a new Stream instance, which is not a collection. If you want to obtain an immutable collection from a stream, you need to use the collect() terminal operation along with the appropriate collector.

Here's a set of basic samples on how to collect a stream to an immutable collection in Java:

1. Collecting to an Immutable List

To collect a stream to an immutable list, you can use the Collectors.toUnmodifiableList() collector:

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

public class ImmutableListExample {
    public static void main(String[] args) {
        List<String> names = Stream.of("Alice", "Bob", "Charlie")
                .collect(Collectors.toUnmodifiableList());

        System.out.println(names); // [Alice, Bob, Charlie]

        // Attempting to modify the list will throw UnsupportedOperationException
        names.add("David"); // throws UnsupportedOperationException
    }
}        

In this example, the Stream.of("Alice", "Bob", "Charlie") creates a stream of strings, and the collect(Collectors.toUnmodifiableList()) collects the stream elements into an unmodifiable list. Any attempt to modify the resulting list will throw an UnsupportedOperationException.

2. Collecting to an Immutable Set

To collect a stream to an immutable set, you can use the Collectors.toUnmodifiableSet() collector:

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ImmutableSetExample {
    public static void main(String[] args) {
        Set<String> names = Stream.of("Alice", "Bob", "Charlie", "Alice")
                .collect(Collectors.toUnmodifiableSet());

        System.out.println(names); // [Bob, Alice, Charlie]

        // Attempting to modify the set will throw UnsupportedOperationException
        names.add("David"); // throws UnsupportedOperationException
    }
}        

In this example, the Stream.of("Alice", "Bob", "Charlie", "Alice") creates a stream of strings with duplicates, and the collect(Collectors.toUnmodifiableSet()) collects the unique stream elements into an unmodifiable set. Any attempt to modify the resulting set will throw an UnsupportedOperationException.

3. Collecting to an Immutable Map

To collect a stream to an immutable map, you can use the Collectors.toUnmodifiableMap() collector along with appropriate key and value mappers:

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ImmutableMapExample {
    public static void main(String[] args) {
        Map<String, Integer> namelengths = Stream.of("Alice", "Bob", "Charlie")
                .collect(Collectors.toUnmodifiableMap(
                        String::toString, // Key mapper
                        String::length    // Value mapper
                ));

        System.out.println(nameLength s); // {Alice=5, Bob=3, Charlie=7}

        // Attempting to modify the map will throw UnsupportedOperationException
        nameLength s.put("David", 5); // throws UnsupportedOperationException
    }
}        

In this example, the Stream.of("Alice", "Bob", "Charlie") creates a stream of strings, and the collect(Collectors.toUnmodifiableMap(String::toString, String::length)) collects the stream elements into an unmodifiable map, where the keys are the strings themselves, and the values are the lengths of the strings. Any attempt to modify the resulting map will throw an UnsupportedOperationException.

I hope this article finds you well. Thank you for reading and see you on the next one!


要查看或添加评论,请登录

社区洞察

其他会员也浏览了