java 8 stream practice problems

Amy 17 Published: 12/24/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!

disadvantages of stream api in java 8

Here are some disadvantages of using Stream API in Java 8:

Inefficiency: While the Stream API is designed to provide a concise and expressive way of processing data, it can sometimes lead to inefficiencies. For instance, if you're working with large datasets, the Stream API's internal operations like map() or filter() may result in excessive memory usage or CPU utilization. Lack of Control: With the Stream API, you sacrifice some control over the processing pipeline. You don't have direct access to intermediate results, and you can't interrupt the stream processing once it's started. This lack of control can be a disadvantage in certain situations where you need more fine-grained control over the processing. Debugging Challenges: The Stream API's lambda-based functions can make it challenging to debug your code. When something goes wrong, it can be difficult to pinpoint the exact problem due to the abstract nature of these functions. Performance Overhead: Although the Stream API is generally faster than traditional iteration methods, there are cases where the performance overhead might be significant. For example, if you're working with small datasets or simple operations, the additional processing required by the Stream API might negate any performance benefits it provides. Inadequate Error Handling: The Stream API doesn't provide built-in error handling mechanisms. This means that you'll need to implement your own error handling strategies, which can be time-consuming and add complexity to your code. Difficulty in Understanding Complex Pipelines: As the pipelines of stream operations become more complex, it's easy to lose sight of what each operation is doing and how they're affecting the overall processing pipeline. This can make it difficult to maintain or modify your code over time. Inability to Interrupt Processing: Unlike traditional iteration methods that allow you to break out of a loop at any point, the Stream API doesn't provide an equivalent way to interrupt the stream processing once it's started. Difficulty in Debugging Multithreaded Pipelines: When working with multithreaded pipelines, it can be challenging to debug issues due to the inherent complexity and variability introduced by concurrent execution of threads. Difficulty in Understanding Side-Effects: Stream API operations that have side-effects, such as modifying external state or throwing exceptions, can make code more difficult to understand and maintain, especially when working with complex pipelines. Inadequate Support for Custom Operations: Although the Stream API provides a rich set of built-in operations, there are cases where you might need custom operations to handle specific processing requirements. However, implementing custom stream operations can be challenging and may require advanced knowledge of Java 8's internal workings.

By being aware of these potential disadvantages, you can better decide whether or not the Stream API is the best choice for your specific use case in Java 8.