0% found this document useful (0 votes)
17 views23 pages

Stream API Coding Ques

Uploaded by

mdpraveen002
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)
17 views23 pages

Stream API Coding Ques

Uploaded by

mdpraveen002
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
You are on page 1/ 23

Stream API questions are commonly asked in Java interviews, especially for Java 8 and

onwards. Here’s a compilation of possible Stream API coding questions with answers:

1. Filter even numbers from a list

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]

2. Convert a list of strings to uppercase

Question: Convert a list of strings to uppercase using Stream.

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]

3. Find the first element greater than 4 in a list

Question: Find the first element in a list that is greater than 4.

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

4. Sum of all elements in a list

Question: Calculate the sum of all elements in a list.


Answer:

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

5. Check if all elements are even

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

6. Convert a list of strings to a single string

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

7. Find the maximum element in a list

Question: Find the maximum element in a list of integers.

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

Question: Sort a list of integers in descending order using Stream.

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]

9. Count the number of strings with length greater than 3

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

10. FlatMap example: Flatten a list of lists

Question: Flatten a list of lists into a single list.

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]

11. Group strings by their length

Question: Group a list of strings by their length.

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]}

12. Remove duplicate elements from a list

Question: Remove duplicates from a list using Stream.

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]

13. Partition a list of integers into even and odd

Question: Partition a list into even and odd numbers.

Answer:

java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
Map<Boolean, List<Integer>> partitioned = numbers.stream()

.collect(Collectors.partitioningBy(n -> n % 2 == 0));


System.out.println(partitioned); // Output: {false=[1, 3, 5, 7], true=[2,
4, 6]}

14. Parallel stream example

Question: Write a parallel stream example to print numbers from a list.

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; }
}

List<Person> people = Arrays.asList(


new Person(1, "John"),
new Person(2, "Jane"),
new Person(3, "Tom")
);

Map<Integer, String> peopleMap = people.stream()

.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:

more scenario based questions please


ChatGPT said:

ChatGPT

Here are more scenario-based questions for the Stream API, which involve slightly more
complex situations and problem-solving techniques using Streams:

1. Find the second highest number from a list

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);

Optional<Integer> secondHighest = numbers.stream()


.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
secondHighest.ifPresent(System.out::println); // Output: 40

2. Group employees by department and calculate the average salary in each


department

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;

public Employee(String name, double salary, String department) {


this.name = name;
this.salary = salary;
this.department = department;
}

public String getDepartment() { return department; }


public double getSalary() { return salary; }
}

List<Employee> employees = Arrays.asList(


new Employee("John", 50000, "IT"),
new Employee("Jane", 60000, "HR"),
new Employee("Tom", 70000, "IT"),
new Employee("Lucy", 55000, "HR")
);

Map<String, Double> avgSalaryByDept = employees.stream()


.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.averagingDouble(Employee::getSalary)));

System.out.println(avgSalaryByDept); // Output: {IT=60000.0, HR=57500.0}

3. Find the longest string in a list

Scenario: Given a list of strings, find the longest string.


Solution:

java
Copy code
List<String> words = Arrays.asList("java", "python", "javascript", "go");

Optional<String> longestWord = words.stream()

.max(Comparator.comparingInt(String::length));
longestWord.ifPresent(System.out::println); // Output: javascript

4. Find the product of all elements in a list

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

5. Find the frequency of each character in a string

Scenario: Given a string, count the frequency of each character and return a map.

Solution:

java
Copy code
String input = "hello world";

Map<Character, Long> frequencyMap = input.chars()


.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));

System.out.println(frequencyMap); // Output: { =1, r=1, d=1, e=1, h=1, l=3,


o=2, w=1}

6. Calculate the total price of items in a shopping cart

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;

public Item(String name, int quantity, double price) {


this.name = name;
this.quantity = quantity;
this.price = price;
}

public double getTotalPrice() {


return quantity * price;
}
}

List<Item> cart = Arrays.asList(


new Item("Apple", 2, 3.00),
new Item("Banana", 5, 1.50),
new Item("Orange", 3, 2.00)
);

double totalPrice = cart.stream()


.mapToDouble(Item::getTotalPrice)
.sum();

System.out.println(totalPrice); // Output: 18.5

7. Find employees with the highest salary in each department

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;

public Employee(String name, double salary, String department) {


this.name = name;
this.salary = salary;
this.department = department;
}

public String getDepartment() { return department; }


public double getSalary() { return salary; }
public String getName() { return name; }
}

List<Employee> employees = Arrays.asList(


new Employee("John", 50000, "IT"),
new Employee("Jane", 60000, "HR"),
new Employee("Tom", 70000, "IT"),
new Employee("Lucy", 55000, "HR")
);
Map<String, Optional<Employee>> highestSalaryByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,

Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))));

highestSalaryByDept.forEach((department, employee) ->


System.out.println(department + ": " + employee.get().getName()));
// Output:
// IT: Tom
// HR: Jane

8. Find the common elements between two lists

Scenario: Given two lists of integers, find the common elements.

Solution:

java
Copy code
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);

List<Integer> commonElements = list1.stream()


.filter(list2::contains)
.collect(Collectors.toList());

System.out.println(commonElements); // Output: [3, 4, 5]

9. Group a list of products by price range

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;

public Product(String name, double price) {


this.name = name;
this.price = price;
}

public double getPrice() { return price; }


}

List<Product> products = Arrays.asList(


new Product("Product A", 30.00),
new Product("Product B", 100.00),
new Product("Product C", 250.00),
new Product("Product D", 80.00)
);

Map<String, List<Product>> groupedByPrice = products.stream()


.collect(Collectors.groupingBy(product -> {
if (product.getPrice() <= 50) return "Low";
else if (product.getPrice() <= 100) return "Medium";
else return "High";
}));

System.out.println(groupedByPrice);
// Output: {Low=[Product A], Medium=[Product B, Product D], High=[Product
C]}

10. Calculate the top 3 highest salaries

Scenario: Given a list of employees, find the top 3 highest salaries.

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")
);

List<Double> top3Salaries = employees.stream()


.map(Employee::getSalary)
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());

System.out.println(top3Salaries); // Output: [90000.0, 80000.0, 70000.0]

11. Check if a list contains duplicate elements

Scenario: Write a code to check if a list contains any duplicate elements.

Solution:

java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 4, 5);

boolean hasDuplicates = numbers.stream()


.distinct()
.count() != numbers.size();

System.out.println(hasDuplicates); // Output: true


12. Partition employees by salary range

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:

reverse a list using stream


ChatGPT 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:

1. Converting the list into a stream.


2. Sorting the list in reverse order using Comparator.reverseOrder().
3. Collecting the result back into a list.

Alternatively, you can use the Collections.reverse() method.

Here’s how you can reverse a list using streams:

Solution 1: Using Collections.reverseOrder() (for ordered elements):


java
Copy code
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> reversedList = numbers.stream()


.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(reversedList); // Output: [5, 4, 3, 2, 1]

Solution 2: Using Collections.reverse() and stream:

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);

List<Integer> reversedList = numbers.stream()


.collect(Collectors.toList());
Collections.reverse(reversedList);

System.out.println(reversedList); // Output: [5, 4, 3, 2, 1]

This method ensures that the original list remains intact, and you create a new reversed list.

4o

You said:

what are the packages need to be imported


ChatGPT said:

ChatGPT

For both solutions to reverse a list using Java Stream, you will need to import the following
packages:

1. Solution 1 (Using Comparator.reverseOrder()):

java
Copy code
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

2. Solution 2 (Using Collections.reverse() and Stream):

java
Copy code
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

Here’s a breakdown of the required packages:

• java.util.Arrays: To use Arrays.asList() method to create a list.


• java.util.Comparator: To use Comparator.reverseOrder() for reversing the list
in streams.
• java.util.List: To work with the List interface.
• java.util.stream.Collectors: To collect the stream result back into a list.
• java.util.Collections: To use Collections.reverse() method to reverse the
list.

These are all standard Java packages, so no external libraries are needed.

4o

You said:

give me more interview coding question with answer


ChatGPT said:

ChatGPT
4o

You said:

i asked streamAPI questions


1/3
ChatGPT said:

ChatGPT

Here are some Stream API coding questions with answers:

1. Filter even numbers from a list using Stream API

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;

public class Main {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [2, 4, 6, 8]
}
}

2. Convert a list of strings to uppercase using Stream API

Scenario: Convert all elements of a list of strings to uppercase.

Solution:

java
Copy code
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {


public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry");
List<String> upperCaseWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upperCaseWords); // Output: [APPLE, BANANA,
CHERRY]
}
}

3. Find the sum of all integers in a list using Stream API

Scenario: Calculate the sum of all integers in a list.

Solution:

java
Copy code
import java.util.Arrays;
import java.util.List;

public class Main {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum); // Output: 15
}
}

4. Sort a list of strings in alphabetical order using Stream API

Scenario: Given a list of strings, sort them in alphabetical order.

Solution:
java
Copy code
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {


public static void main(String[] args) {
List<String> words = Arrays.asList("banana", "apple", "cherry");
List<String> sortedWords = words.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(sortedWords); // Output: [apple, banana,
cherry]
}
}

5. Find the distinct elements in a list using Stream API

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;

public class Main {


public static void main(String[] args) {
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]
}
}
``
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:

1. Group people by age using Stream API


Scenario: Given a list of Person objects with name and age, group them by age.

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;
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class Main {


public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 30),
new Person("David", 25)
);

Map<Integer, List<Person>> peopleByAge = people.stream()

.collect(Collectors.groupingBy(person -> person.age));


System.out.println(peopleByAge);
// Output: {25=[Bob (25), David (25)], 30=[Alice (30), Charlie
(30)]}
}
}

2. Convert List of Person objects to a Map using Stream API

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;
}
}

public class Main {


public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 30)
);

Map<String, Integer> nameToAgeMap = people.stream()

.collect(Collectors.toMap(person -> person.name, person -> person.age));

System.out.println(nameToAgeMap);
// Output: {Alice=30, Bob=25, Charlie=30}
}
}

3. Find the oldest person in a list using Stream API

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;

Person(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class Main {


public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
Person oldest = people.stream()
.max(Comparator.comparingInt(person ->
person.age))
.orElseThrow(NoSuchElementException::new);

System.out.println(oldest); // Output: Charlie (35)


}
}

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;

public class Main {


public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "apple",
"orange", "banana", "apple");

Map<String, Long> wordCount = words.stream()

.collect(Collectors.groupingBy(word -> word, Collectors.counting()));

System.out.println(wordCount);
// Output: {banana=2, orange=1, apple=3}
}
}

5. Find the second highest number in a list using Stream API

Scenario: Given a list of integers, find the second highest number.

Solution:

java
Copy code
import java.util.*;
import java.util.stream.Collectors;

public class Main {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 5, 9, 3, 7, 5);

int secondHighest = numbers.stream()


.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.orElseThrow(NoSuchElementException::new);

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;

public class Main {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9,
10);

Map<Boolean, List<Integer>> partitioned = numbers.stream()

.collect(Collectors.partitioningBy(n -> n % 2 == 0));

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

Scenario: Given a list of Person objects, find the average age.

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;
}
}

public class Main {


public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);

double averageAge = people.stream()


.collect(Collectors.averagingInt(person -
> person.age));

System.out.println(averageAge); // Output: 30.0


}
}

8. Check if all persons are older than 18 using Stream API

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;

Person(String name, int age) {


this.name = name;
this.age = age;
}
}

public class Main {


public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);

boolean allAdults = people.stream()


.allMatch(person -> person.age > 18);

System.out.println(allAdults); // Output: true


}
}

9. Flatten a list of lists using Stream API

Scenario: Given a list of lists, flatten it into a single list.

Solution:
java
Copy code
import java.util.*;
import java.util.stream.Collectors;

public class Main {


public static void main(String[] args) {
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("A", "B"),
Arrays.asList("C", "D"),
Arrays.asList("E", "F")
);

List<String> flattenedList = listOfLists.stream()


.flatMap(List::stream)

.collect(Collectors.toList());

System.out.println(flattenedList); // Output: [A, B, C, D, E, F]


}
}

10. Sort a list of Person objects by name using Stream API

Scenario: Given a list of Person objects, sort them alphabetically by name.

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;
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class Main {


public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Charlie", 30),
new Person("Alice", 25),
new Person("Bob", 35)
);

List<Person> sortedByName = people.stream()


.sorted(Comparator.comparing(person -> person.name))
.collect(Collectors.toList());

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:

Find the duplicate number in an array using stream


ChatGPT 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;

public class Main {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 2, 6, 3};

Set<Integer> seen = new HashSet<>();


List<Integer> duplicates = Arrays.stream(numbers) // Convert the
array to stream
.filter(n -> !seen.add(n)) //
Filter out duplicates
.boxed() // Convert int to
Integer
.collect(Collectors.toList()); //
Collect duplicates into a list

System.out.println(duplicates); // Output: [2, 3]


}
}

Explanation:

1. Convert the array to stream: Arrays.stream(numbers) converts the array to a


stream of integers.
2. Tracking duplicates: The seen.add(n) returns false if the element is already
present in the set, so !seen.add(n) will filter out duplicates.
3. Collect the result: The .boxed() converts the primitive int to Integer and then
collects the duplicate numbers into a list using Collectors.toList().

Output:
csharp
Copy code
[2, 3]

This code finds and returns all duplicate elements from the array.

You might also like