Category: Java programming question
-
Java Program reverse each word in a String
You can reverse each word in a string using Java 8 Streams by splitting the string into words, reversing each word, and then joining them back. Output:
-
Java program to find the common elements between two arrays
You can find common elements between two arrays using Java 8 Streams by filtering elements present in both arrays. Below are two approaches: Approach 1: Using filter() and contains() (For Small Arrays) This approach works well when the second array is small since contains() runs in O(n) time. Output: Approach 2: Using Set for Better…
-
Java program to sort a list of strings according to the increasing order of their length
Alternative: Using Comparator.comparing() A more concise way:
-
Java program to find the second largest number in an integer array
Output: Using reduce() (Without Sorting) This approach finds the largest and second largest in one pass, making it more efficient (O(n) time complexity).
-
Java 8 program to get the three maximum and three minimum numbers from a given list of integers
You can use Java 8 Streams to get the three maximum and three minimum numbers from a given list of integers by using sorted(), limit(), and distinct() if needed. Output: Explanation: Handling Duplicates If you want unique numbers, use distinct() before sorting:
-
Merge two unsorted arrays into a single sorted array without duplicates
You can merge two unsorted arrays into a single sorted array without duplicates using Java 8 Streams. The key steps are: For Integer Object Arrays (Integer[]) Output: For Primitive int Arrays (int[]): Since IntStream doesn’t support distinct() on boxed values directly, use: Output:
-
Merge two unsorted arrays into a single sorted array using Java 8 streams
You can merge two unsorted arrays and sort them using Java 8 Streams with Stream.concat() and sorted(). Output: Explanation: Descending Order If you want the merged array sorted in reverse order, just use:
-
Java 8 program to find the maximum and minimum of a list of integers
You can use Java 8 Streams to find the maximum and minimum values from a list of integers using the max() and min() methods with Comparator.naturalOrder(). Output: Alternative Using mapToInt (Primitive Stream):
-
Java program to print the numbers from a given list of integers that are multiples of 5
You can use Java 8 Streams to filter and print numbers that are multiples of 5 using the filter() method. Output:
-
Java program to join a list of strings with ‘[‘ as prefix, ‘]’ as suffix, and ‘,’ as delimiter
You can use Java 8 Streams with Collectors.joining() to join a list of strings with a specified prefix, suffix, and delimiter. Output: Explanation:
