Java Stream API : Interview Programs - Part 1

Java Stream API : Interview Programs - Part 1

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

Write a program to find the second largest element in a list using Java Stream API without sorting the list.

To find the second largest element in a list without sorting the list, you can use the Java Stream API. One approach is to use the reduce method to keep track of both the largest and second largest elements as you iterate over the list. Here's a program that demonstrates this:

import java.util.Arrays;
import java.util.List;

public class SecondLargestElement {

public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 5, 20, 8, 15);

Integer secondLargest = numbers.stream()
.reduce(Integer.MIN_VALUE, (first, second) -> {
if (second > first) {
return second;
} else {
return first;
}
});

System.out.println("Second largest element is: " + secondLargest);
}
}

In this program, we start with the initial value of Integer.MIN_VALUE to ensure that the initial largest value is less than any element in the list. We then iterate over each element in the list and compare it with the current largest value. If the element is larger, we update the largest value to be that element. By the end of the iteration, the secondLargest variable will contain the second largest element in the list.


advertisement

Write a program to remove consecutive duplicate elements from a list using Java Stream API.

You can use the Java Stream API to remove consecutive duplicate elements from a list. Here's a simple program to demonstrate this:

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, 4, 5, 6, 6, 7, 8, 8, 8);

List<Integer> result = removeConsecutiveDuplicates(numbers);
System.out.println(result);
}

public static List<Integer> removeConsecutiveDuplicates(List<Integer> list) {
return list.stream()
.reduce((prev, curr) -> {
if (prev.equals(curr)) {
return prev;
} else {
return curr;
}
})
.map(last -> list.stream()
.reduce(new ElementsWithLast<>(last), ElementsWithLast::accumulate, ElementsWithLast::combine)
.getElements())
.orElse(List.of());
}

static class ElementsWithLast<T> {
private T last;
private List<T> elements;

public ElementsWithLast(T last) {
this.last = last;
this.elements = List.of(last);
}

public ElementsWithLast(T last, List<T> elements) {
this.last = last;
this.elements = elements;
}

public ElementsWithLast<T> accumulate(T t) {
if (last.equals(t)) {
return this;
} else {
var newElements = new java.util.ArrayList<>(elements);
newElements.add(t);
return new ElementsWithLast<>(t, newElements);
}
}

public ElementsWithLast<T> combine(ElementsWithLast<T> other) {
if (last.equals(other.last)) {
return new ElementsWithLast<>(last, elements);
} else {
var newElements = new java.util.ArrayList<>(elements);
newElements.addAll(other.elements);
return new ElementsWithLast<>(other.last, newElements);
}
}

public List<T> getElements() {
return elements;
}
}
}

This program uses a custom accumulator (ElementsWithLast) to keep track of the last element encountered while iterating through the list. If the current element is the same as the last element, it skips adding it to the result list.


advertisement

Write a program to Generate a list of prime numbers using Java Stream API

You can generate a list of prime numbers using the Java Stream API by creating a method that checks if a number is prime and then using the IntStream to generate a stream of numbers and filter out the non-prime numbers. Here's an example program that demonstrates this:

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

public class PrimeNumberGenerator {

public static void main(String[] args) {
int n = 50; // Generate prime numbers up to n
List<Integer> primeNumbers = generatePrimeNumbers(n);
System.out.println("Prime numbers up to " + n + ": " + primeNumbers);
}

public static List<Integer> generatePrimeNumbers(int n) {
return IntStream.rangeClosed(2, n)
.filter(PrimeNumberGenerator::isPrime)
.boxed()
.collect(Collectors.toList());
}

public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}

This program generates prime numbers up to a given limit n using the generatePrimeNumbers method, which uses the isPrime method to check if a number is prime. The isPrime method uses a basic prime number checking algorithm that iterates from 2 to the square root of the number to check for factors.


advertisement


Write a program to Find missing numbers from a range using Java Stream API

You can use the Java Stream API to find missing numbers from a range. Here's a program that demonstrates this:

import java.util.Arrays;
import java.util.stream.IntStream;

public class MissingNumbersFinder {
public static void main(String[] args) {
int[] numbers = {1, 2, 4, 6, 9};
int start = 1;
int end = 10;

System.out.println("Missing numbers between " + start + " and " + end + ":");
findMissingNumbers(numbers, start, end)
.forEach(System.out::println);
}

public static IntStream findMissingNumbers(int[] numbers, int start, int end) {
int[] allNumbers = IntStream.rangeClosed(start, end).toArray();

return Arrays.stream(allNumbers)
.filter(num -> Arrays.binarySearch(numbers, num) < 0);
}
}

This program first defines an array of numbers and a range (start and end). Then, it creates an array containing all numbers in the specified range using IntStream.rangeClosed(start, end).toArray(). Finally, it uses the Stream API to filter out the numbers that are present in the given array and prints the missing numbers.

Post a Comment

Previous Post Next Post