CodeGym /Courses /JAVA 25 SELF /Transforming Collections with Streams

Transforming Collections with Streams

JAVA 25 SELF
Level 30, Lesson 4
Available

1. Converting List → Set and back

Let’s recall why we need collection transformations at all. Often, in real-world tasks we need to:

  • Get unique elements from a list (for example, an email list → a set of unique addresses).
  • Build a map (Map)—for example, from a list of names get a map “name → name length”.
  • Join elements into a single string (e.g., for neat output).

Previously, you had to write a lot of code with loops, conditions, and temporary collections. With the Stream API it became simpler and… more elegant!

Example: get a set of unique names from a list

Suppose we have a list of names (someone might have entered themselves twice—happens!):

List<String> names = List.of("Anna", "Sergey", "Anna", "Maria", "Ivan", "Sergey");

Our task is to get a collection where each name appears only once, i.e., a set (Set). With the Stream API this takes literally one line:

Set<String> uniqueNames = names.stream()
    .collect(Collectors.toSet());
System.out.println(uniqueNames);

Output:

[Maria, Ivan, Anna, Sergey]

(Order in a Set is not guaranteed—don’t be surprised if you see a different order.)

What about the other way: Set → List?

Sometimes you need the opposite—to turn a set into a list (for example, to sort or to access by index):

List<String> namesList = uniqueNames.stream()
    .collect(Collectors.toList());
System.out.println(namesList);

2. Converting to a Map: Collectors.toMap()

Example: from a list of names build a Map “name → name length”

Sometimes you want to be not just a programmer but a real cartographer—build maps! Let’s try:

List<String> names = List.of("Anna", "Sergey", "Maria", "Ivan");

Map<String, Integer> nameToLength = names.stream()
    .collect(Collectors.toMap(
        name -> name,         // key: the name itself
        name -> name.length() // value: name length
    ));

System.out.println(nameToLength);

Output:

{Maria=5, Ivan=4, Anna=4, Sergey=6}

Important point: duplicate keys

If the source list contains the same names, attempting to collect them into a Map will throw an IllegalStateException: Duplicate key. Java doesn’t like it when you try to put two values under the same key.

How to handle duplicates?
You can specify what to do when keys collide—for example, keep the first value or the last:

List<String> names = List.of("Anna", "Sergey", "Anna", "Maria", "Ivan", "Sergey");

Map<String, Integer> nameToLength = names.stream()
    .collect(Collectors.toMap(
        name -> name,
        name -> name.length(),
        (oldValue, newValue) -> oldValue // keep the first value
    ));

System.out.println(nameToLength);

Now the program won’t crash, and only the first occurrence of each name will end up in the Map.

Example: Map with objects

Let’s make it a bit more interesting: we have a list of users, and we want to build a Map “name → user”:

class User {
    String name;
    int age;
    User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String toString() {
        return name + " (" + age + ")";
    }
}

// Example user list
List<User> users = List.of(
    new User("Anna", 25),
    new User("Sergey", 30),
    new User("Maria", 22)
);

Map<String, User> nameToUser = users.stream()
    .collect(Collectors.toMap(
        user -> user.name,
        user -> user
    ));

System.out.println(nameToUser);

Output:

{Maria=Maria (22), Anna=Anna (25), Sergey=Sergey (30)}

3. Joining into a string: Collectors.joining()

Sometimes you don’t want to just collect a collection, but produce a nice string for user output or logs. For example, join all names with a comma:

List<String> names = List.of("Anna", "Sergey", "Maria", "Ivan");

String result = names.stream()
    .collect(Collectors.joining(", "));

System.out.println(result);

Output:

Anna, Sergey, Maria, Ivan

You can add a prefix and suffix

String result = names.stream()
    .collect(Collectors.joining(", ", "List: [", "]"));

System.out.println(result);

Output:

List: [Anna, Sergey, Maria, Ivan]

4. Terminal operations: forEach, collect, count, anyMatch, allMatch, noneMatch

Method forEach

We’re already familiar with forEach: this operation performs an action for each element of the stream.

names.stream().forEach(name -> System.out.println("Hello, " + name + "!"));

Method collect

Collects elements into a collection, a string, or another structure. The most common operation is collecting into a List or Set using Collectors.toList() and Collectors.toSet().

Method count

Counts the number of elements in the stream.

long count = names.stream()
    .filter(name -> name.length() > 4)
    .count();
System.out.println("Names longer than 4 letters: " + count);

Methods anyMatch, allMatch, noneMatch

Check whether a condition holds for at least one element (anyMatch), for all (allMatch), or for none (noneMatch).

boolean hasShortName = names.stream()
    .anyMatch(name -> name.length() < 4);
System.out.println("Is there a short name? " + hasShortName);

boolean allLong = names.stream()
    .allMatch(name -> name.length() > 3);
System.out.println("Are all names longer than 3 letters? " + allLong);

boolean noneIvan = names.stream()
    .noneMatch(name -> name.equals("Ivan"));
System.out.println("No Ivan present? " + noneIvan);

Output:

Is there a short name? false
Are all names longer than 3 letters? true
No Ivan present? false

5. Terminal vs. intermediate operations: recap the concepts

Intermediate operations (filter, map, distinct, sorted, limit, skip, peek) return a new Stream, and you can build chains.

Terminal operations (forEach, collect, count, anyMatch, allMatch, noneMatch, reduce, findFirst, findAny) end the stream—there will be no further results!

Example chain:

List<String> result = users.stream()
    .filter(user -> user.age > 20)
    .map(user -> user.name.toUpperCase())
    .distinct()
    .sorted()
    .collect(Collectors.toList());

System.out.println(result);

Output:

[ANNA, IVAN, MARIA, SERGEY]

6. Common mistakes when transforming collections with streams

Mistake #1: Not handling duplicate keys in toMap
If the source collection contains duplicate keys and you use Collectors.toMap() without an explicit handler, the program will throw an exception. In such cases always specify a merge function:

// Keep the last value
.toMap(keyMapper, valueMapper, (oldVal, newVal) -> newVal)

Mistake #2: Using forEach instead of collect
Sometimes beginners try to “collect” a collection using forEach, for example:

List<String> list = new ArrayList<>();
names.stream().forEach(name -> list.add(name)); // Works, but this is not the Stream way!

It’s better to use collect(Collectors.toList())—it’s safer and cleaner.

Mistake #3: Trying to reuse a stream
A stream can be used only once. After a terminal operation (for example, collect, forEach) attempting to continue working with the same Stream will lead to an IllegalStateException.

Mistake #4: Violating the “no side effects” principle
Intermediate operations should be pure (without modifying external variables). Don’t change anything outside the stream inside map or filter.

Mistake #5: Ignoring ordering in Set and Map
If element order matters, use appropriate collections—such as LinkedHashSet, TreeMap—and specify the right collector.

1
Task
JAVA 25 SELF, level 30, lesson 4
Locked
Counting Unique Conference Attendees 🧑‍🤝‍🧑
Counting Unique Conference Attendees 🧑‍🤝‍🧑
1
Task
JAVA 25 SELF, level 30, lesson 4
Locked
Building a List of User Profiles Prioritizing the First Entry 👤
Building a List of User Profiles Prioritizing the First Entry 👤
1
Survey/quiz
Stream API Basics, level 30, lesson 4
Unavailable
Stream API Basics
Stream API Basics
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION