Stream API Coding Ques
Stream API Coding Ques
onwards. Here’s a compilation of possible Stream API coding questions with answers:
Question: Write a code to filter out even numbers from a list of integers.
Answer:
java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
Answer:
java
Copy code
List<String> words = Arrays.asList("hello", "world", "java");
List<String> uppercaseWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(uppercaseWords); // Output: [HELLO, WORLD, JAVA]
Answer:
java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 5, 6, 7);
Optional<Integer> firstGreaterThanFour = numbers.stream()
.filter(n -> n > 4)
.findFirst();
firstGreaterThanFour.ifPresent(System.out::println); // Output: 5
java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum); // Output: 15
Question: Write a program to check if all elements in the list are even.
Answer:
java
Copy code
List<Integer> numbers = Arrays.asList(2, 4, 6, 8);
boolean allEven = numbers.stream()
.allMatch(n -> n % 2 == 0);
System.out.println(allEven); // Output: true
Question: Convert a list of strings to a single string where each element is separated by a
comma.
Answer:
java
Copy code
List<String> words = Arrays.asList("Java", "Stream", "API");
String result = words.stream()
.collect(Collectors.joining(", "));
System.out.println(result); // Output: Java, Stream, API
Answer:
java
Copy code
List<Integer> numbers = Arrays.asList(3, 5, 9, 1, 7);
Optional<Integer> max = numbers.stream()
.max(Integer::compareTo);
max.ifPresent(System.out::println); // Output: 9
8. Sort a list of integers in descending order
Answer:
java
Copy code
List<Integer> numbers = Arrays.asList(5, 3, 9, 1, 7);
List<Integer> sortedNumbers = numbers.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(sortedNumbers); // Output: [9, 7, 5, 3, 1]
Question: Count the number of strings with a length greater than 3 in a list.
Answer:
java
Copy code
List<String> words = Arrays.asList("one", "three", "four", "six");
long count = words.stream()
.filter(s -> s.length() > 3)
.count();
System.out.println(count); // Output: 3
Answer:
java
Copy code
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("a", "b", "c"),
Arrays.asList("d", "e", "f"),
Arrays.asList("g", "h", "i")
);
List<String> flatList = listOfLists.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println(flatList); // Output: [a, b, c, d, e, f, g, h, i]
Answer:
java
Copy code
List<String> words = Arrays.asList("one", "three", "four", "six");
Map<Integer, List<String>> groupedByLength = words.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(groupedByLength); // Output: {3=[one, six], 4=[four],
5=[three]}
Answer:
java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
List<Integer> distinctNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(distinctNumbers); // Output: [1, 2, 3, 4, 5]
Answer:
java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
Answer:
java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.parallelStream()
.forEach(System.out::println);
15. Create a map from a list of objects
Question: Create a Map from a list of objects based on some criteria (e.g., id).
Answer:
java
Copy code
class Person {
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { return id; }
public String getName() { return name; }
}
.collect(Collectors.toMap(Person::getId, Person::getName));
System.out.println(peopleMap); // Output: {1=John, 2=Jane, 3=Tom}
These examples cover common Stream API coding scenarios you might encounter in
interviews, focusing on filtering, mapping, reducing, and handling collections.
4o
You said:
ChatGPT
Here are more scenario-based questions for the Stream API, which involve slightly more
complex situations and problem-solving techniques using Streams:
Scenario: Given a list of integers, find the second highest number without sorting the list
twice.
Solution:
java
Copy code
List<Integer> numbers = Arrays.asList(10, 20, 50, 30, 40);
Scenario: Given a list of Employee objects with fields name, salary, and department, group
employees by department and calculate the average salary per department.
Solution:
java
Copy code
class Employee {
String name;
double salary;
String department;
java
Copy code
List<String> words = Arrays.asList("java", "python", "javascript", "go");
.max(Comparator.comparingInt(String::length));
longestWord.ifPresent(System.out::println); // Output: javascript
Scenario: Given a list of integers, find the product of all elements using Stream.
Solution:
java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int product = numbers.stream()
.reduce(1, (a, b) -> a * b);
System.out.println(product); // Output: 120
Scenario: Given a string, count the frequency of each character and return a map.
Solution:
java
Copy code
String input = "hello world";
Scenario: Given a list of Item objects (with fields name, quantity, and price), calculate the
total price of all items.
Solution:
java
Copy code
class Item {
String name;
int quantity;
double price;
Scenario: Given a list of employees, find the employee with the highest salary in each
department.
Solution:
java
Copy code
class Employee {
String name;
double salary;
String department;
Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))));
Solution:
java
Copy code
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);
Scenario: Group a list of Product objects (with fields name and price) into three categories:
low, medium, and high price.
Solution:
java
Copy code
class Product {
String name;
double price;
System.out.println(groupedByPrice);
// Output: {Low=[Product A], Medium=[Product B, Product D], High=[Product
C]}
Solution:
java
Copy code
List<Employee> employees = Arrays.asList(
new Employee("John", 50000, "IT"),
new Employee("Jane", 60000, "HR"),
new Employee("Tom", 70000, "IT"),
new Employee("Lucy", 80000, "HR"),
new Employee("Max", 90000, "Sales")
);
Solution:
java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 4, 5);
Scenario: Partition a list of employees into two groups: those who earn more than $50,000
and those who earn less than or equal to $50,000.
Solution:
java
Copy code
Map<Boolean, List<Employee>> partitionedBySalary = employees.stream()
.collect(Collectors.partitioningBy(e -> e.getSalary() > 50000));
System.out.println(partitionedBySalary);
// Output: {false=[Employee with salary <= 50000], true=[Employee with
salary > 50000]}
These scenario-based questions help reinforce core Stream API functionalities such as
filtering, mapping, reducing, and handling collections in different business-related or
complex data manipulation tasks.
4o
You said:
ChatGPT
To reverse a list using Java Stream API, you can't directly reverse a list with the built-in
stream methods since the stream itself does not have an order-modifying function like
reverse. However, you can achieve this by:
If the order is important and you want to preserve the original list's order, here's another
approach using Collections.reverse().
java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
This method ensures that the original list remains intact, and you create a new reversed list.
4o
You said:
ChatGPT
For both solutions to reverse a list using Java Stream, you will need to import the following
packages:
java
Copy code
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
java
Copy code
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
These are all standard Java packages, so no external libraries are needed.
4o
You said:
ChatGPT
4o
You said:
ChatGPT
Scenario: Given a list of integers, filter out only the even numbers.
Solution:
java
Copy code
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
Solution:
java
Copy code
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
Solution:
java
Copy code
import java.util.Arrays;
import java.util.List;
Solution:
java
Copy code
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
Scenario: Given a list with duplicate elements, find the distinct elements.
Solution:
java
Copy code
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
.collect(Collectors.toList());
System.out.println(distinctNumbers); // Output: [1, 2, 3, 4, 5]
}
}
``
4o
You said:
give more object and stream API interview problems with answer
ChatGPT said:
ChatGPT
Here are more object-related and Stream API coding interview questions with answers:
Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
class Person {
String name;
int age;
@Override
public String toString() {
return name + " (" + age + ")";
}
}
Scenario: Given a list of Person objects, convert the list into a map with the name as the key
and the age as the value.
Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
System.out.println(nameToAgeMap);
// Output: {Alice=30, Bob=25, Charlie=30}
}
}
Scenario: Given a list of Person objects, find the person with the maximum age.
Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
class Person {
String name;
int age;
@Override
public String toString() {
return name + " (" + age + ")";
}
}
4. Count the number of occurrences of each word in a list using Stream API
Scenario: Given a list of strings, count the frequency of each unique string.
Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
System.out.println(wordCount);
// Output: {banana=2, orange=1, apple=3}
}
}
Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
System.out.println(secondHighest); // Output: 7
}
}
6. Partition a list of integers into even and odd numbers using Stream API
Scenario: Given a list of integers, partition the list into even and odd numbers.
Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
System.out.println(partitioned);
// Output: {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8, 10]}
}
}
7. Find the average age of a list of Person objects using Stream API
Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
class Person {
String name;
int age;
Scenario: Given a list of Person objects, check if all persons are older than 18.
Solution:
java
Copy code
import java.util.*;
class Person {
String name;
int age;
Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
.collect(Collectors.toList());
Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
class Person {
String name;
int age;
@Override
public String toString() {
return name + " (" + age + ")";
}
}
System.out.println(sortedByName);
// Output: [Alice (25), Bob (35), Charlie (30)]
}
}
These problems cover various object and Stream API usage scenarios and are useful for
interviews to test your understanding of Stream API manipulation, such as sorting, filtering,
mapping, and collecting operations.
4o
You said:
ChatGPT
Here's how you can find the duplicate number in an array using Stream API:
Scenario:
Given an array of integers, find the duplicate numbers using the Stream API.
Solution:
You can use a Set to track the numbers as you iterate through the stream and filter out the
duplicates.
java
Copy code
import java.util.*;
import java.util.stream.Collectors;
Explanation:
Output:
csharp
Copy code
[2, 3]
This code finds and returns all duplicate elements from the array.