Java Stream Coding Interview Questions

Q. Find the longest string in a list of strings using Java streams:

List<String> strings = Arrays
.asList("apple", "banana", "cherry", "date", "grapefruit");
Optional<String> longestString = strings
.stream()
.max(Comparator.comparingInt(String::length));

Q. Calculate the average age of a list of Person objects using Java streams:

List<Person> persons = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
);
double averageAge = persons.stream()
.mapToInt(Person::getAge)
.average()
.orElse(0);

Q. Check if a list of integers contains a prime number using Java streams:

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

private void printPrime() {
List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10, 11, 12, 13, 14, 15);
boolean containsPrime = numbers.stream()
.anyMatch(this::isPrime);
System.out.println("List contains a prime number: " + containsPrime);

}

Q. Merge two sorted lists into a single sorted list using Java streams:

List<Integer> list1 = Arrays.asList(1, 3, 5, 7, 9);
List<Integer> list2 = Arrays.asList(2, 4, 6, 8, 10);
List<Integer> mergedList = Stream.concat(list1.stream(), list2.stream())
.sorted()
.collect(Collectors.toList());

Q. Find the intersection of two lists using Java streams:

List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);
List<Integer> intersection = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());

Q. Remove duplicates from a list while preserving the order using Java streams:

List<Integer> numbersWithDuplicates = Arrays.asList(1, 2, 3, 2, 4, 1, 5, 6, 5);
List<Integer> uniqueNumbers = numbersWithDuplicates
.stream()
.distinct()
.collect(Collectors.toList());

Q. Given a list of transactions, find the sum of transaction amounts for each day using Java streams:

List<Transaction> transactions = Arrays.asList(
new Transaction("2022-01-01", 100),
new Transaction("2022-01-01", 200),
new Transaction("2022-01-02", 300),
new Transaction("2022-01-02", 400),
new Transaction("2022-01-03", 500)
);

Map<String, Integer> sumByDay = transactions
.stream()
.collect(Collectors.groupingBy(Transaction::getDate,
Collectors.summingInt(Transaction::getAmount)));

Q. Find the kth smallest element in an array using Java streams:

int[] array = {4, 2, 7, 1, 5, 3, 6};
int k = 3; // Find the 3rd smallest element
int kthSmallest = Arrays.stream(array)
.sorted()
.skip(k - 1)
.findFirst()
.orElse(-1);

Q. Given a list of strings, find the frequency of each word using Java streams:

List<String> words = Arrays.asList("apple", "banana", "apple", "cherry", 
"banana", "apple");
Map<String, Long> wordFrequency = words
.stream()
.collect(Collectors
.groupingBy(Function.identity(), Collectors.counting())
);

Q. Implement a method to calculate the Fibonacci sequence using Java streams:

Stream<Long> fibonacci = Stream.iterate(
new long[]{0, 1}, f -> new long[]{f[1], f[0] + f[1]})
.mapToLong(f -> f[0]);
// Print first 10 Fibonacci numbers
fibonacci.limit(10).forEach(System.out::println);

Q. Find the median of a list of integers using Java streams:

List<Integer> numbers = Arrays.asList(5, 2, 1, 3, 4);
OptionalDouble median = numbers.stream()
.sorted()
.mapToInt(Integer::intValue)
.collect(IntStatistics.summaryStatistics())
.getMedian();
System.out.println("Median: " + median.getAsDouble());

Q. Given a list of strings, find the longest common prefix using Java streams:

List<String> strings = Arrays.asList("flower", "flow", "flight");
String longestCommonPrefix = strings.stream()
.reduce((s1, s2) -> {
int length = Math.min(s1.length(), s2.length());
int i = 0;
while (i < length && s1.charAt(i) == s2.charAt(i)) {
i++;
}
return s1.substring(0, i);
})
.orElse("");
System.out.println("Longest common prefix: " + longestCommonPrefix);

Q. Find the maximum product of two integers in an array using Java streams:

int[] array = {1, 4, 3, 6, 2, 7, 8};
int maxProduct = IntStream.range(0, array.length)
.mapToObj(i -> IntStream.range(i + 1, array.length)
.map(j -> array[i] * array[j])
.max()
.orElse(Integer.MIN_VALUE))
.max(Integer::compare)
.orElse(Integer.MIN_VALUE);
System.out.println("Maximum product: " + maxProduct);

Q. Implement a method to find all anagrams in a list of strings using Java streams:

List<String> words = Arrays.asList("listen", "silent", "hello",
"world", "night", "thing");
Map<String, List<String>> anagrams = words.stream()
.collect(Collectors.groupingBy(str -> {
char[] chars = str.toCharArray();
Arrays.sort(chars);
return new String(chars);
}));
System.out.println("Anagrams: " + anagrams);

Q. Given a list of intervals, find the total covered length using Java streams:

List<Interval> intervals = Arrays.asList(new Interval(1, 3),
new Interval(5, 8), new Interval(10, 12));
int totalCoveredLength = intervals.stream()
.mapToInt(interval -> interval.getEnd() - interval.getStart())
.sum();
System.out.println("Total covered length: " + totalCoveredLength);

Q. Find the number of occurrences of a given character in a list of strings using Java streams:

List<String> strings = Arrays.asList("apple", "banana", "orange", 
"grape", "melon");
char target = 'a';
long occurrences = strings.stream()
.flatMapToInt(CharSequence::chars)
.filter(c -> c == target)
.count();
System.out.println("Occurrences of '" + target + "': " + occurrences);

Q. Given a list of integers, find all pairs of numbers that sum up to a given target using Java streams:

List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10);
int target = 12;
Set<String> pairs = numbers.stream()
.flatMap(i -> numbers.stream().
map(j -> i + j == target ? "(" + i + ", " + j + ")" : ""))
.filter(s -> !s.isEmpty())
.collect(Collectors.toSet());
System.out.println("Pairs that sum up to " + target + ": " + pairs);

Q. Given a list of integers, find all non duplicate integers using Java streams:

List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 4, 5, 6, 4, 7, 8, 9, 9);

// Count the occurrences of each number
Map<Integer, Long> frequencyMap = numbers.stream()
.collect(Collectors
.groupingBy(Function.identity(), Collectors.counting())
);

// Filter out non-duplicate numbers
numbers.stream()
.filter(number -> frequencyMap.get(number) == 1)
.forEach(System.out::println);

Q. Given a list of strings, find the longest string using Java streams.

List<String> strings = Arrays.asList("apple", "banana", "orange",
"grape", "kiwi");

String longestString = strings.stream()
.max((s1, s2) -> Integer.compare(s1.length(), s2.length()))
.orElse(null);

These questions demonstrate more complex stream operations and can be quite challenging to implement.

Q. Implement a method to partition a list into two groups based on a predicate using Java streams:        

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Map<Boolean, List<Integer>> partitioned = numbers
.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
List<Integer> evenNumbers = partitioned.get(true);
List<Integer> oddNumbers = partitioned.get(false);
System.out.println("Even numbers: " + evenNumbers);
System.out.println("Odd numbers: " + oddNumbers);                                    

Post a Comment

Previous Post Next Post