ShimSeongbo / study

0 stars 0 forks source link

[Modern Java In Action] Summary #3

Open ShimSeongbo opened 1 year ago

ShimSeongbo commented 1 year ago

Java StreamAPI - Modern Java in Action Summary

Introduction to StreamAPI

Streams, introduced in Java 8, represent a sequence of objects. They are designed to make data processing patterns readable and concise.

Key Features

Core Stream Operations

1. Filtering

Use the filter method:

List<String> filteredNames = names.stream()
                                  .filter(n -> n.startsWith("A"))
                                  .collect(Collectors.toList());

2. Mapping

With the map method, you can transform data:

List<String> uppercasedNames = names.stream()
                                    .map(String::toUpperCase)
                                    .collect(Collectors.toList());

3. Finding & Matching

-anyMatch: Check if a predicate matches at least one element. -allMatch: Check if a predicate matches all elements. -noneMatch: Check if no elements match the given predicate.

4. Reducing

The reduce method combines stream elements:

int totalCalories = menu.stream()
                        .map(Dish::getCalories)
                        .reduce(0, Integer::sum);

5. Collecting

Gather data from a stream:

List<String> collectedNames = names.stream()
                                   .collect(Collectors.toList());

Parallel Streams

To convert a stream to a parallel stream:

Stream<String> parallelNames = names.parallelStream();

Conclusion

Java's StreamAPI is a powerful and expressive tool that can significantly simplify data processing tasks, making your code more readable and maintainable.

References

ShimSeongbo commented 1 year ago

[핵심 정리]