Java Stream API : Interview Programs - Part 6

Java Stream API : Interview Programs  - Part 6

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

Write a program to Find the median of a list of numbers using Java Stream API


Here's a program that uses the Java Stream API to find the median of a list of numbers:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MedianCalculator {

public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);

double median = findMedian(numbers);
System.out.println("Median: " + median);
}

public static double findMedian(List<Integer> numbers) {
Collections.sort(numbers);
int size = numbers.size();

if (size % 2 == 0) {
int mid1 = numbers.get(size / 2 - 1);
int mid2 = numbers.get(size / 2);
return (double) (mid1 + mid2) / 2;
} else {
return numbers.get(size / 2);
}
}
}

This program first sorts the list of numbers using Collections.sort(). Then, it calculates the median based on whether the list size is even or odd. If the size is even, it calculates the average of the two middle elements. If the size is odd, it returns the middle element directly.


advertisement

Write a program to Transpose a matrix using Java Stream API

You can transpose a matrix using the Java Stream API by converting the matrix into a stream of rows, then transposing it, and finally collecting the transposed matrix back into a 2D array. Here's how you can do it:

import java.util.Arrays;

public class MatrixTranspose {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int[][] transposedMatrix = transpose(matrix);

// Print the transposed matrix
for (int[] row : transposedMatrix) {
System.out.println(Arrays.toString(row));
}
}

public static int[][] transpose(int[][] matrix) {
return Arrays.stream(matrix)
.reduce((a, b) -> IntStream.range(0, Math.max(a.length, b.length))
.mapToObj(i -> i < a.length ? a[i] : new int[a.length])
.mapToInt(row -> row.length > 0 ? row[0] : 0)
.zipWith(IntStream.range(0, Math.max(a.length, b.length))
.mapToObj(i -> i < b.length ? b[i] : new int[b.length])
.mapToInt(row -> row.length > 0 ? row[0] : 0), (x, y) -> {
int[] result = new int[]{x, y};
return result;
}))
.orElse(new int[0][]);
}
}

This program will transpose the given matrix and print the transposed matrix. Note that this method assumes that the matrix is rectangular (all rows have the same length). If your matrix is not rectangular, you may need to modify the transpose method to handle that case.


advertisement

Write a program to Generate permutations of a list using Java Stream API

You can generate permutations of a list using Java Stream API by first creating a recursive method to generate permutations and then using the Stream API to generate all possible permutations. Here's an example:

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

public class Permutations {

public static void main(String[] args) {
List<Integer> list = List.of(1, 2, 3);
List<List<Integer>> permutations = generatePermutations(list);
permutations.forEach(System.out::println);
}

public static <T> List<List<T>> generatePermutations(List<T> list) {
if (list.isEmpty()) {
return List.of(List.of());
}

return list.stream()
.flatMap(element ->
generatePermutations(list.stream().filter(e -> !e.equals(element)).collect(Collectors.toList()))
.stream()
.map(permutation -> {
List<T> perm = new ArrayList<>(permutation);
perm.add(element);
return perm;
})
)
.collect(Collectors.toList());
}
}

This program generates and prints all permutations of the list [1, 2, 3]. You can replace List.of(1, 2, 3) with any other list you want to generate permutations for.


advertisement

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

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

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

public class MissingCharactersFinder {

public static void main(String[] args) {
String input = "abcdefghijklmnopqrstuvwxyz";
String range = "hijklmnopqrstuvwx";

String missingCharacters = findMissingCharacters(input, range);
System.out.println("Missing characters: " + missingCharacters);
}

public static String findMissingCharacters(String input, String range) {
return range.chars()
.filter(c -> input.indexOf(c) == -1)
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
}
}

In this program, the findMissingCharacters method takes two strings: input and range. It uses the Stream API to convert the range string to an IntStream of character values. Then, it filters out the characters that are not present in the input string and collects the missing characters into a new string. Finally, it returns the string containing the missing characters.


advertisement

Post a Comment

Previous Post Next Post