Stream mapping in Java provides multiple transformation techniques to manipulate data efficiently. Understanding these transformations is crucial for effective stream processing.
Simple Element Conversion
List<String> names = Arrays.asList("alice", "bob", "charlie");
List<String> capitalizedNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Result: ["ALICE", "BOB", "CHARLIE"]
Handling Nested Collections
List<List<String>> nestedList = Arrays.asList(
Arrays.asList("Java", "Python"),
Arrays.asList("JavaScript", "TypeScript")
);
List<String> flattenedLanguages = nestedList.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
// Result: ["Java", "Python", "JavaScript", "TypeScript"]
graph TD
A[Nested Collections] --> B[flatMap()]
B --> C[Flattened Stream]
Converting Between Object Types
class User {
private String name;
private int age;
// Constructor, getters
}
class UserDTO {
private String username;
private boolean isAdult;
// Constructor, getters
}
List<User> users = // ... some list of users
List<UserDTO> userDTOs = users.stream()
.map(user -> new UserDTO(
user.getName(),
user.getAge() >= 18
))
.collect(Collectors.toList());
Transformation |
Purpose |
Use Case |
map() |
One-to-one transformation |
Simple element conversion |
flatMap() |
One-to-many transformation |
Flattening nested collections |
mapToInt() |
Mapping to primitive int |
Numeric calculations |
mapToDouble() |
Mapping to primitive double |
Floating-point operations |
Advanced Mapping Techniques
Conditional Mapping
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> processedNumbers = numbers.stream()
.map(num -> num % 2 == 0 ? num * 2 : num)
.collect(Collectors.toList());
// Result: [1, 4, 3, 8, 5]
- Use
map()
for simple transformations
- Prefer
flatMap()
for complex nested structures
- Consider performance for large datasets
LabEx Recommendation
Explore stream mapping transformations through interactive coding exercises on LabEx to enhance your Java functional programming skills.