Java Stream API : Interview Programs - Part 4

Java Stream API : Interview Programs  - Part 4


Java Stream API : Interview Programs  - Part 4
Java Stream API : Interview Programs  - Part 4

Write a program to Find the intersection of two lists using Java Stream API.

You can use Java Stream API to find the intersection of two lists by converting them into streams and then using filter to retain only the common elements. Here's a simple program to achieve that:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);

List<Integer> list2 = new ArrayList<>();
list2.add(3);
list2.add(4);
list2.add(5);
list2.add(6);

List<Integer> intersection = findIntersection(list1, list2);
System.out.println("Intersection: " + intersection);
}

public static <T> List<T> findIntersection(List<T> list1, List<T> list2) {
return list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
}
}

This program will output:

Intersection: [3, 4]

This code takes two lists list1 and list2, and finds their intersection using Java Stream API. It then prints out the elements that are common to both lists.


advertisement

Write a program to Compute factorial of each element in a list using Java Stream API

You can use the Java Stream API to compute the factorial of each element in a list. Here's a program that demonstrates this:

import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FactorialCalculator {

public static BigInteger factorial(int n) {
if (n == 0 || n == 1) {
return BigInteger.ONE;
}
return BigInteger.valueOf(n).multiply(factorial(n - 1));
}

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

List<BigInteger> factorials = numbers.stream()
.map(n -> factorial(n))
.collect(Collectors.toList());

System.out.println("Factorials: " + factorials);
}
}

In this program, we first define a factorial method to compute the factorial of a given number using recursion. Then, we create a list of integers and use the stream method to convert the list into a stream. We use the map method to apply the factorial method to each element in the stream, and finally, we collect the results into a list using the collect method.


advertisement

Write a program to Group objects in a list by multiple criteria using Java Stream API

You can use the Java Stream API to group objects in a list by multiple criteria by chaining `Collectors.groupingBy` collectors. Here's an example program that demonstrates this:

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

class Student {
private String name;
private int age;
private String department;

public Student(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public String getDepartment() {
return department;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", department='" + department + '\'' +
'}';
}
}

public class Main {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", 20, "Math"),
new Student("Bob", 21, "Math"),
new Student("Charlie", 22, "Physics"),
new Student("David", 20, "Physics"),
new Student("Eve", 21, "Physics")
);

Map<String, Map<Integer, List<Student>>> groupedStudents = students.stream()
.collect(Collectors.groupingBy(Student::getDepartment,
Collectors.groupingBy(Student::getAge)));

groupedStudents.forEach((department, ageMap) -> {
System.out.println("Department: " + department);
ageMap.forEach((age, studentList) -> {
System.out.println("\tAge: " + age);
studentList.forEach(System.out::println);
});
});
}
}

In this example, `Student` objects are grouped first by department and then by age. The `groupedStudents` map contains the result of this grouping, where the outer map's key is the department, and the inner map's key is the age. The inner map's value is a list of students matching the department and age criteria.


advertisement

Write a program to Find the closest pair of elements in a list using Java Stream API


To find the closest pair of elements in a list using the Java Stream API, you can create a custom method that compares all pairs of elements in the list and returns the pair with the smallest difference. Here's a sample program to achieve this:

import java.util.*;
import java.util.stream.*;

public class ClosestPair {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 4, 7, 10, 15);

Optional<Pair> closestPair = findClosestPair(numbers);
if (closestPair.isPresent()) {
System.out.println("Closest pair: " + closestPair.get());
} else {
System.out.println("No pair found");
}
}

public static Optional<Pair> findClosestPair(List<Integer> numbers) {
return IntStream.range(0, numbers.size() - 1)
.flatMap(i -> IntStream.range(i + 1, numbers.size())
.mapToObj(j -> new Pair(numbers.get(i), numbers.get(j))))
.min(Comparator.comparingInt(Pair::getDifference));
}

static class Pair {
private final int first;
private final int second;

public Pair(int first, int second) {
this.first = first;
this.second = second;
}

public int getDifference() {
return Math.abs(first - second);
}

@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
}

This program defines a `Pair` class to hold a pair of integers and calculates the difference between them. The `findClosestPair` method generates all pairs of elements in the list and finds the pair with the smallest difference using the `min` method of the Stream API.


advertisement

Post a Comment

Previous Post Next Post