java 8 stream practice problems

Sandy 121 Published: 08/20/2024

java 8 stream practice problems

I'd be happy to help you with some Java 8 Stream practice problems. Here are five problems for you to try:

Problem 1: Filtering a List

Given a list of integers, use the stream() method to filter out all even numbers and return a new list containing only the odd numbers.

Example:

List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

List oddNumbers = numbers.stream()

.filter(n -> n % 2 != 0)

.collect(Collectors.toList());

Problem 2: Mapping a List

Given a list of strings, use the stream() method to map each string to its uppercase equivalent and return a new list containing only the uppercase strings.

Example:

List words = Arrays.asList("hello", "world", "java");

List upperCaseWords = words.stream()

.map(String::toUpperCase)

.collect(Collectors.toList());

Problem 3: Reducing a List

Given a list of integers, use the stream() method to calculate the sum of all numbers in the list using the reduce() method.

Example:

List numbers = Arrays.asList(1, 2, 3, 4, 5);

int total = numbers.stream()

.reduce(0, (a, b) -> a + b);

Problem 4: Sorting and Limiting a List

Given a list of strings, use the stream() method to sort the list in descending order by length and limit the result to only show the top 3 longest strings.

Example:

List words = Arrays.asList("hello", "world", "java", "python");

List longWords = words.stream()

.sorted((a, b) -> Integer.compare(b.length(), a.length()))

.limit(3)

.collect(Collectors.toList());

Problem 5: Grouping and Aggregating a List

Given a list of objects representing students with attributes name, grade, and major, use the stream() method to group the students by major and calculate the average grade for each major.

Example:

List students = Arrays.asList(

new Student("John", 90, "CS"),

new Student("Jane", 85, "Math"),

new Student("Bob", 95, "CS"),

new Student("Alice", 80, "Math")

);

Map<String, Double> averageGradesByMajor = students.stream()

.collect(Collectors.groupingBy(Student::getMajor,

Collectors.averagingInt(Student::getGrade)));

These problems should give you a good starting point for practicing Java 8 Streams. Remember to use the stream() method to create a Stream, and then chain together methods like filter(), map(), reduce(), sorted(), limit(), and others to perform complex operations on your data.

Good luck!

advantages and disadvantages of streams in java

I'm happy to provide a detailed response in English!

Advantages of Streams in Java:

Concise Code: Streams enable you to write concise code that is easy to read and maintain. You can chain multiple operations together, making your code more readable. Functional Programming: Streams introduce functional programming concepts to Java, enabling you to write declarative code that focuses on what you want to achieve, rather than how.

Lazy Evaluation: Stream pipelines are lazily evaluated, meaning that each operation is only executed when the previous one has completed. This can improve performance and reduce memory usage. Parallelization: Streams provide a way to parallelize operations, which can lead to significant performance improvements for computationally intensive tasks. Reduced Memory Usage: By processing data in chunks, streams can reduce memory usage and avoid loading large datasets into memory at once. Improved Error Handling: Streams provide better error handling capabilities, as exceptions are propagated through the pipeline, making it easier to diagnose and handle errors.

Disadvantages of Streams in Java:

Performance Overhead: While streams can improve performance for some operations, they can also introduce a performance overhead due to the creation of intermediate objects. Complexity: Streams can add complexity to your code, especially if you're new to functional programming or haven't worked with streams before. Limited Support: Not all Java APIs and libraries support streams, which can limit their usefulness in certain situations. Debugging Challenges: Debugging stream pipelines can be challenging due to the lazy evaluation of operations and the potential for exceptions being thrown at runtime. ** Limited Control:** Streams provide a level of abstraction that can make it harder to control the exact behavior of your code, which can be frustrating if you're used to having fine-grained control over your code's execution. Incompatibility with Legacy Code: If you have existing Java code that doesn't use streams, integrating stream-based code into your legacy codebase can be challenging.

Overall, streams in Java offer many advantages for processing data in a concise and efficient manner. However, they also introduce some potential disadvantages, such as performance overhead, complexity, limited support, and debugging challenges. By understanding the strengths and weaknesses of streams, you can use them effectively to improve your Java programming skills.

Please note that this response is written in English only, as per your request.