java stream api interview questions

Cary 154 Published: 07/19/2024

java stream api interview questions

Here are some Java Stream API interview questions with answers:

1. What is the main idea behind the Java Stream API?

The Java Stream API provides a way to process data as streams, which can be thought of as sequences of elements that can be manipulated using various operations. It's designed to simplify and improve the processing of large amounts of data in a more functional and concise manner.

2. How do you filter a stream in Java?

You can use the filter() method provided by the Stream API to filter a stream. For example:

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

List filteredWords = words.stream()

.filter(word -> word.length() > 4)

.collect(Collectors.toList());

In this example, the filter() method is used to filter a stream of strings and keep only those with a length greater than 4.

3. How do you map a stream in Java?

You can use the map() method provided by the Stream API to map a stream. For example:

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

List upperCaseWords = words.stream()

.map(String::toUpperCase)

.collect(Collectors.toList());

In this example, the map() method is used to map a stream of strings and convert each string to uppercase.

4. How do you reduce a stream in Java?

You can use the reduce() method provided by the Stream API to reduce a stream. For example:

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

int sum = numbers.stream()

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

In this example, the reduce() method is used to reduce a stream of integers and compute their sum.

5. What are some common Stream API operations?

Some common Stream API operations include:

filter(): filters a stream map(): maps a stream reduce(): reduces a stream collect(): collects a stream into a collection or other type of object findFirst(): finds the first element in a stream findAny(): finds any element in a stream

6. How do you handle exceptions in a Stream API pipeline?

You can use the try-matching method provided by the Stream API to handle exceptions in a stream pipeline. For example:

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

List processedWords = words.stream()

.map(word -> {

try {

return processWord(word);

} catch (Exception e) {

return null;

}

})

.filter(Objects::nonNull)

.collect(Collectors.toList());

In this example, the try-matching method is used to map a stream of strings and handle exceptions in the processWord() method. The filter() method is then used to filter out any null values that may result from handling an exception.

7. How do you convert a Stream API pipeline into a collection?

You can use the collect() method provided by the Stream API to convert a stream pipeline into a collection. For example:

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

List upperCaseWords = words.stream()

.map(String::toUpperCase)

.collect(Collectors.toList());

In this example, the collect() method is used to convert a stream pipeline into a collection of uppercase strings.

8. What are some common use cases for the Java Stream API?

Some common use cases for the Java Stream API include:

Processing large amounts of data in a scalable and efficient manner Simplifying code by avoiding explicit loops and conditional statements Improving code readability by using concise and expressive operations Enhancing code maintainability by using lambda expressions to encapsulate complex logic

9. How do you use the distinct() method in Java?

You can use the distinct() method provided by the Stream API to remove duplicate elements from a stream. For example:

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

List uniqueWords = words.stream()

.distinct()

.collect(Collectors.toList());

In this example, the distinct() method is used to remove duplicate elements from a stream of strings and return a list of unique words.

10. How do you use the sorted() method in Java?

You can use the sorted() method provided by the Stream API to sort a stream of elements. For example:

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

List sortedWords = words.stream()

.sorted()

.collect(Collectors.toList());

In this example, the sorted() method is used to sort a stream of strings in ascending order and return a list of sorted words.

java stream map

The power of Java Stream API! map is a fantastic method that allows you to transform the elements of an Stream into another type, and it's extremely useful when working with data transformations.

What does map do?

The map method in Java Stream API applies a given function to each element of a stream, returning a new stream where each element is the result of applying that function. In other words, it takes an input stream, applies some transformation (mapping) to each element, and produces a new output stream.

Example usage

Suppose we have a list of integers representing ages:

List ages = Arrays.asList(25, 30, 35, 20, 40);

We want to create a new stream where each age is replaced with its corresponding string representation (e.g., "Twenty-Five" for 25). We can use the map method to achieve this:

String[] strings = ages.stream()

.map(age -> {

if (age < 30) {

return "Young";

} else if (age >= 40) {

return "Old";

} else {

return "Middle-Aged";

}

})

.toArray(String[]::new);

System.out.println(Arrays.toString(strings));

// Output: [Young, Young, Middle-Aged, Young, Old]

In this example, the map method takes each age and applies a function that returns one of three strings ("Young", "Middle-Aged", or "Old") based on the age value. The resulting stream is then collected into an array of strings.

More examples

Here are some more examples to illustrate the power of map:

Converting strings to uppercase: We can use map to convert all string elements in a stream to uppercase:
List names = Arrays.asList("john", "jane", "bob");

String[] upperCaseNames = names.stream()

.map(String::toUpperCase)

.toArray(String[]::new);

Extracting specific information: Suppose we have a list of objects representing people, and each person has a name and age:
List people = Arrays.asList(

new Person("John", 25),

new Person("Jane", 30),

new Person("Bob", 35)

);

String[] names = people.stream()

.map(person -> person.getName())

.toArray(String[]::new);

In this example, we use map to extract just the name from each person object and collect them into a string array.

Transforming data: We can also use map to perform complex transformations on data. For instance, let's say we have a list of numbers representing temperatures in Celsius:
List temps = Arrays.asList(20.5, 25.2, 30.1);

String[] tempStrings = temps.stream()

.map(temp -> String.format("%.1f°C", temp))

.toArray(String[]::new);

Here, we use map to transform each temperature value into a string representation (e.g., "20.5°C" for 20.5) and collect them into an array of strings.

Conclusion

The map method in Java Stream API is a powerful tool that allows you to transform data streams with ease. By applying a function to each element, you can perform various transformations, such as converting types, extracting specific information, or performing complex calculations. With map, the possibilities are endless!