An AI tool suggested the following code to process a large dataset using Java Streams. However, it's inefficient. Identify the problem and suggest a more efficient solution.

Java interview question for Advanced practice.

Answer

Move the filter() operation before the map() operation.

Explanation

The inefficiency lies in the order of stream operations. The current code converts all strings in the list to uppercase (map) and then throws many of them away (filter). It is much more efficient to filter the list first to reduce its size, and then perform the map operation only on the elements that are needed. Moving .filter() before .map() is the correct optimization.

Related Questions