Alright πŸš€ β€” here’s your Java .map() & .flatMap() Cheat Sheet

so you can instantly decide which one to use in real-world coding.

Java .map() & .flatMap() Cheat Sheet1. Basic TransformationsGoalUseExampleConvert each element to another type.map()Stream<String> β†’ Stream<Integer> (lengths)Modify each element but keep same type.map()Stream<String> β†’ Stream<String> (uppercase)

Java

コードをコピー
list.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

2. Extracting Fields from ObjectsGoalUseExampleGet a property from each object.map()List<User> β†’ List<String> (usernames)

Java

コードをコピー
users.stream()
     .map(User::getUsername)
     .collect(Collectors.toList());

3. Converting to Collections or ArraysGoalUseExampleEach element β†’ a collection (nested).map()Stream<String> β†’ Stream<List<String>>Each element β†’ multiple elements (flattened).flatMap()Stream<String> β†’ Stream<String>

Java

コードをコピー
// map() β†’ nested lists
Stream<List<String>> nested = phrases.stream()
    .map(p -> Arrays.asList(p.split(" "))); // Stream<List<String>>

// flatMap() β†’ flattened
List<String> flat = phrases.stream()
    .flatMap(p -> Arrays.stream(p.split(" ")))
    .collect(Collectors.toList());

4. Working with OptionalsGoalUseExampleTransform value inside Optional.map()Optional<User> β†’ Optional<String>Flatten nested Optional.flatMap()Optional<Optional<String>> β†’ Optional<String>

Java

コードをコピー
Optional<User> user = Optional.of(new User("john"));

// map()
Optional<String> name = user.map(User::getUsername);

// flatMap()
Optional<String> safeName = user.flatMap(u -> Optional.ofNullable(u.getUsername()));

5. Database / API CallsGoalUseExampleOne record β†’ one DTO.map()Stream<Entity> β†’ Stream<DTO>One record β†’ multiple DTOs.flatMap()Stream<Entity> β†’ Stream<DTO> (flattened)

Java

コードをコピー
// map: one-to-one
entities.stream()
        .map(EntityMapper::toDto)
        .collect(Collectors.toList());

// flatMap: one-to-many
entities.stream()
        .flatMap(e -> e.getOrders().stream())
        .collect(Collectors.toList());
  • 6. Rule of ThumbUse .map() when your function returns a single value for each input.
  • Use .flatMap() when your function returns a stream, array, or collection and you want to flatten it.

πŸ’‘ Pro Tip:

If you see Stream<Stream<T>>Stream<List<T>>, or Optional<Optional<T>> β€”

you probably need .flatMap().

If you want, I can now prepare a one-page PDF quick reference with diagrams + examples for .map() and .flatMap() so you can keep it handy while coding.

Do you want me to make that PDF for you?

← Back to Learning Journey