0% found this document useful (0 votes)
11 views2 pages

Java 8 Streams Assignment Solutions

Uploaded by

suriyajai2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Java 8 Streams Assignment Solutions

Uploaded by

suriyajai2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java 8 Streams Mini Assignment with Answers

Q1: Filter Even Numbers

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);

[Link]()

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

.forEach([Link]::println);

Q2: Convert Strings to Uppercase

List<String> names = [Link]("jai", "suriya", "kumar");

List<String> upperNames = [Link]()

.map(String::toUpperCase)

.collect([Link]());

[Link](upperNames); // [JAI, SURIYA, KUMAR]

Q3: Get Squares of Numbers

List<Integer> nums = [Link](2, 3, 4);

List<Integer> squares = [Link]()

.map(n -> n * n)

.collect([Link]());

[Link](squares); // [4, 9, 16]

Q4: Sum All Numbers

List<Integer> nums = [Link](1, 2, 3, 4);

int sum = [Link]()

.reduce(0, Integer::sum);

[Link](sum); // 10

Q5: Sort Numbers

List<Integer> nums = [Link](5, 1, 4, 2, 3);

[Link]()

.sorted()

.forEach([Link]::println);

Q6: Remove Duplicates


List<Integer> nums = [Link](1, 2, 2, 3, 4, 4, 5);

[Link]()

.distinct()

.forEach([Link]::println);

Q7: Limit Output

List<String> names = [Link]("Ram", "Sita", "Ravi", "Radha", "Gita");

[Link]()

.limit(3)

.forEach([Link]::println);

Q8: Skip First 2 Items

List<String> names = [Link]("Ram", "Sita", "Ravi", "Radha");

[Link]()

.skip(2)

.forEach([Link]::println);

Q9: Check if Any Name Starts with 'R'

List<String> names = [Link]("Geeta", "Sita", "Ravi", "Radha");

boolean result = [Link]()

.anyMatch(name -> [Link]("R"));

[Link](result); // true

Q10: Count Names with 4 Letters

List<String> names = [Link]("Ram", "Ravi", "Lina", "Geet", "Kavi");

long count = [Link]()

.filter(name -> [Link]() == 4)

.count();

[Link](count); // 3

Common questions

Powered by AI

The `limit()` method in Java 8 streams is beneficial when processing large datasets as it allows for the restriction of the number of elements processed. By limiting the output, one can perform efficient operations such as sample testing, previewing data results, or resource-saving computations by reducing memory and processing time. This method can help in performance optimization, especially in scenarios where only a subset of data is necessary for analysis or display .

The `anyMatch()` function is particularly useful in scenarios where a quick, boolean validation of elements is required, such as checking if any element in a collection satisfies a specific condition. It provides a logical advantage by terminating the stream processing as soon as a match is found, thus improving performance by preventing unnecessary computations on the remaining elements. This can be highly efficient in large datasets where matches might occur early in the iteration .

The `distinct()` method in Java 8 streams is used to filter out duplicate elements from a data stream. As each element is processed, duplicates are automatically identified and discarded, which simplifies the task of ensuring unique entries in a dataset. This method is significant in data processing as it maintains data integrity and ensures accurate results, especially in cases where data sources may have redundancy .

The `sorted()` function in Java 8 streams provides efficient data organization by leveraging the internal iteration mechanism, which abstracts the sorting logic. The stream API can sort data in parallel, taking advantage of multicore processors, which can significantly improve performance compared to traditional single-threaded sorting loops. Additionally, `sorted()` naturally integrates with functional programming paradigms, offering cleaner and more concise code .

The `count()` function in Java 8 streams is a simple yet powerful tool in data analytics, providing an efficient way to quantify elements that meet certain criteria. For example, counting elements of a particular length in a string list. Its primary limitation is that it consumes the stream, meaning the stream cannot be reused afterward, and it might not be as efficient when complex conditions or large datasets are involved without prior filtering to reduce the dataset size first .

Java 8 streams allow for a declarative approach to filtering even numbers from a list. By using the `stream()` method on a list and the `filter()` method with a lambda expression `(n -> n % 2 == 0)`, even numbers are selected and processed without modifying the original dataset. This method is beneficial because it enhances readability, supports parallel execution, and adheres to the principles of functional programming by treating functions as first-class citizens .

Stream operations like `filter()` and `forEach()` do not modify the original collection in Java 8. Instead, they operate on a stream, which is a sequence of elements supporting sequential and parallel aggregate operations. This reveals the functional programming nature of streams, emphasizing immutability and non-destructive transformations. As a result, the original data remains unchanged, allowing for safer multi-use and concurrent operations .

The `skip()` method in Java streams enhances collection manipulation by allowing for the exclusion of a specified number of initial elements in a stream. This is particularly useful in applications involving pagination, where specific subsets of data need to be displayed based on offset values. By using `skip()`, developers can easily implement pagination logic without altering the core data structure, making it efficient and flexible for dynamic data retrieval .

Using the `reduce` method in a Java 8 stream to calculate the sum of numbers provides several advantages. It abstracts the accumulation logic into a single method call, improving code clarity and reducing errors. The `reduce(0, Integer::sum)` expression neatly handles the initial value and accumulation process, making it ideal for functional programming. It also allows for easier parallel computation, as streams can be processed in parallel without explicit threading logic, potentially enhancing performance .

Mapping strings to uppercase using Java 8 streams improves code efficiency and readability by abstracting loop logic within the `map()` method. This allows for a single line transformation of all elements, as opposed to multiple lines needed for a traditional loop, reducing boilerplate code. Additionally, leveraging method reference `String::toUpperCase` simplifies the conversion process. This approach also enhances parallelism due to inherent stream capabilities, potentially improving performance on large datasets .

You might also like