💻JAVA 8 Interview Programs and Coding Challenges

A cup of JAVA coffee with NeeSri
24 min readJan 30, 2024

--

Hi Readers,

I have explained useful programs using java8.

🔴1. Fibonacci series

The Fibonacci series (or Fibonacci sequence) is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence looks like this:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

import java.util.stream.Stream;

public class FibonacciExample {
public static void main(String[] args) {
// Generate Fibonacci series using Java 8 streams

Stream.iterate(new int[] {0, 1},
fib -> new int[] {fib[1], fib[0] + fib[1]})
.limit(10) // Limit the number of elements in the stream
.mapToInt(fib -> fib[0]) // Extract the first element (fibonacci number)
.forEach(System.out::println); // Print each Fibonacci number
}
}
//--- Output->
0
1
1
2
3
5
8
13
21
34

------------OR---------------------

int n = 10; // Number of Fibonacci numbers

// Generate Fibonacci series using Stream.iterate()
List<Integer> fibonacciSeries =
Stream.iterate(new int[]{0, 1},
f -> new int[]{f[1], f[0] + f[1]})
.limit(n) // Limit to n elements
.map(f -> f[0]) // Extract first value of each pair
.collect(Collectors.toList()); // Collect as a list

// Reverse the list
Collections.reverse(fibonacciSeries);

// Print the Reverse Fibonacci Series
fibonacciSeries.forEach(num -> System.out.print(num + " "));


In this example:

  • We use .limit(10) to limit the stream to the first 10 Fibonacci numbers.
  • We use .mapToInt(fib -> fib[0]) ->Since the iteration creates pairs {a, b}, we only need the first value (a) from each pair.
  • Finally, we use .forEach(System.out::println) to print each Fibonacci number.

When you run this code, it will output the first 10 Fibonacci numbers.

Reverse Fibonacci Series

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

public class ReverseFibonacci {
public static void main(String[] args) {
int n = 10; // Number of Fibonacci numbers

// Generate Fibonacci series using Stream.iterate()
List<Integer> fibonacciSeries =
Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]})
.limit(n)
.map(f -> f[0])
.collect(Collectors.toList());

// Reverse the list
Collections.reverse(fibonacciSeries);

// Print the Reverse Fibonacci Series
fibonacciSeries.forEach(num -> System.out.print(num + " "));
}
}

— — — — — OR — — — — — — — —





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

public class ReverseFibonacci {
public static void main(String[] args) {
int limit = 10;

List<Integer> reversedFibonacci = Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]})
.limit(limit)
.map(f -> f[0])
.collect(Collectors.collectingAndThen
(Collectors.toList(),
list ->
{ Collections.reverse(list);
return list; }));

System.out.println("Reversed Fibonacci Series: "
+ reversedFibonacci);
}
}
//----OUTPUT---//

Reversed Fibonacci Series: [34, 21, 13, 8, 5, 3, 2, 1, 1, 0]

🔴Generate a Fibonacci series in reverse order using Java 8 Streams, where the user provides an input number(Print only the last 5 numbers in reverse order).

import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Collections;

public class ReverseFibonacciStream {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number (max 5 digits): ");
int maxLimit = scanner.nextInt();

if (maxLimit > 99999) {
System.out.println("Number exceeds the limit of 5 digits.");
return;
}

// Generate Fibonacci series using Java 8 Streams
List<Integer> fibonacciList =
Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]})
.map(f -> f[0])
.filter(n -> n <= maxLimit) // Java 8 alternative to `takeWhile()`
.collect(Collectors.toList());

// Reverse the list
Collections.reverse(fibonacciList);

// Print using Streams
String result = fibonacciList.stream()
.map(String::valueOf)
.collect(Collectors.joining(", "));

System.out.println("Reverse Fibonacci Series: " + result);
scanner.close();
}
}

Example Output

Enter a number (max 5 digits): 1234
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.Arrays.copyOf(Arrays.java:3512)
at java.base/java.util.Arrays.copyOf(Arrays.java:3481)
at java.base/java.util.ArrayList.grow(ArrayList.java:237)
at java.base/java.util.ArrayList.grow(ArrayList.java:244)
at java.base/java.util.ArrayList.add(ArrayList.java:454)
at java.base/java.util.ArrayList.add(ArrayList.java:467)
at java.base/java.util.stream.Collectors$$Lambda$23/0x000000010008cb18.accept(Unknown Source)

How This Uses Java 8 Streams

Stream.iterate() generates Fibonacci numbers
map(f -> f[0]) extracts the first number of the Fibonacci pair
filter(n -> n <= maxLimit) restricts numbers within user input (Java 8 alternative to takeWhile())
collect(Collectors.toList()) stores numbers in a list
Collections.reverse() reverses the list
collect(Collectors.joining(", ")) joins numbers into a formatted string

🚀 Fixing OutOfMemoryError: Java heap space in Java 8 Fibonacci Stream

You’re getting OutOfMemoryError: Java heap space because your Stream.iterate() generates infinite Fibonacci numbers without stopping.

🔹 Why Not Use Stream.iterate()?

Problem with Stream.iterate()

Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]})

-> Generates infinite numbers before applying .filter().
-> Causes OutOfMemoryError because it never stops.

Fixed Code (Java 8 Compatible)

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

public class ReverseFibonacci {
public static void main(String[] args) {
// Taking user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to generate Fibonacci series: ");
int input = scanner.nextInt();
scanner.close();

// Generate Fibonacci series and print in reverse order
List<Integer> fibonacciSeries = generateFibonacci(input);
System.out.println("Fibonacci Series in Reverse Order: " + fibonacciSeries);
}

private static List<Integer> generateFibonacci(int max) {
List<Integer> fibonacci = new ArrayList<>();
fibonacci.add(0);
fibonacci.add(1);

// Generate Fibonacci numbers up to 'max'
int next;
while ((next = fibonacci.get(fibonacci.size() - 1) + fibonacci.get(fibonacci.size() - 2)) <= max) {
fibonacci.add(next);
}

// Keep only last 5 Fibonacci numbers
int size = fibonacci.size();
List<Integer> lastFive = fibonacci.subList(Math.max(0, size - 5), size);

// Reverse the list
Collections.reverse(lastFive);
return lastFive;
}
}
List<Integer> lastFive = fibonacci.subList(Math.max(0, size - 5), size);

Used Collections.reverse() for proper ordering

  • More efficient than sorted(Comparator.reverseOrder()).

🔹 Example Execution

Enter a number to generate Fibonacci series: 100

Generated Fibonacci Series (Before Reverse)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Output (Last 5 in Reverse Order)
Fibonacci Series in Reverse Order: [89, 55, 34, 21, 13]

🔹 Why This Fix Works?

No infinite loop → Prevents memory issues.
Keeps only the last 5 numbers → Uses subList().
Java 8 compatible → No need for Java 9+ features like .takeWhile().
Efficient memory usage → No unnecessary operations.

🔴2. Find the Square of Each Element in a List:

Question: Given a list of integers, use Java 8 streams to find the square of each element.

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

List<Integer> squares = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());

System.out.println(squares); // Output: [1, 4, 9, 16, 25]

🔴3. Filter Even Numbers from a List:

Question: Given a list of integers, use Java 8 streams to filter out the even numbers.

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

List<Integer> even= numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(even);
--------Output------
[2, 4, 6, 8]

🔴4. Sum of Squares of Even Numbers:

Question: Given a list of integers, find the sum of the squares of even numbers.

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

int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * n)
.sum();

System.out.println(sum); // Output: 120

🔴5. Check if a List Contains a Specific Element:

Question: Given a list of strings, check if it contains the word “Java”.

List<String> words = Arrays.asList("Python", "JavaScript", "Java", "C++");

boolean containsJava = words.stream()
.anyMatch("Java"::equals);

System.out.println(containsJava); // Output: true

🔴6. Find the Average of a List of Doubles:

List<Double> doubles = Arrays.asList(1.5, 2.5, 3.5, 4.5, 5.5);
double average = doubles.stream()
.mapToDouble(Double::doubleValue)
.average()
.orElse(0.0);

doubles.stream() — Converts the List to a stream of Double elements.

.mapToDouble(Double::doubleValue)- Uses the mapToDouble operation to convert each Double element to a primitive double. This is done by invoking the doubleValue() method on each Double object.

.average() — Calculates the average of the elements in the DoubleStream. The result is an OptionalDouble that may or may not contain the average value

.orElse(0.0) — Uses orElse to provide a default value (0.0) if the stream is empty or if no average is present in the OptionalDouble. In other words, it ensures that the average variable is assigned a value, either the calculated average or the default value.

Overall, this code snippet demonstrates the use of Java 8 streams to calculate the average of a list of Double values. The use of mapToDouble is necessary to convert the stream of Double objects to a DoubleStream before calculating the average. The orElse method is employed to handle the case where the stream is empty, ensuring a default value is provided.

🔴Java 8 Lambda Function to Filter Even Numbers Greater Than 500

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

public class FilterEvenNumbers {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(100, 250, 501, 600, 750, 800, 900, 120);

// Using Stream and Lambda to filter even numbers > 500
List<Integer> filteredList = filterEvenAndGreaterThan500(numbers);

// Output the result
System.out.println("Filtered Numbers: " + filteredList);
}

public static List<Integer> filterEvenAndGreaterThan500(List<Integer> numbers) {
return numbers.stream()
.filter(n -> n > 500 && n % 2 == 0) // Lambda to filter even numbers > 500
.collect(Collectors.toList()); // Collect to list
}
}
//----OUTPUT-----//
Filtered Numbers: [600, 750, 800, 900]

— — — Alternative: Using Method Reference — — -

If you want a cleaner approach, use a method reference:- It Improves code readability by separating the filtering logic into a method.

public static List<Integer> filterEvenAndGreaterThan500(List<Integer> numbers) {
return numbers.stream()
.filter(FilterEvenNumbers::isEvenAndGreaterThan500)
.collect(Collectors.toList());
}

private static boolean isEvenAndGreaterThan500(int n) {
return n > 500 && n % 2 == 0;
}

🔴7. How do you find frequency of each character in a string using Java 8 streams?

You can find the frequency of each character in a string using Java 8 streams by leveraging the Collectors.groupingBy collector. Here's an example:

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CharacterFrequency {

public static void main(String[] args) {
String inputString = "programming is fun";

// Using Java 8 streams to find the frequency of each character
Map<Character, Long> frequencyMap = inputString.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));

// Displaying the frequency of each character
frequencyMap.forEach((character, frequency) ->
System.out.println("Character: " + character + ", Frequency: " + frequency));
}
}

Explanation:

1. inputString.chars():

  • inputString: This is a String variable containing the input string.
  • The chars() method is called on the String object, which returns an IntStream of Unicode code points representing the characters in the string.
  • In Java, each character in a string is represented by a Unicode code point, which is an integer value.
IntStream codePoints = inputString.chars();

2. .mapToObj(c -> (char) c):

  • .mapToObj(...): This part is a stream operation that transforms each element of the IntStream to a corresponding char object.
  • c -> (char) c: This is a lambda expression. For each integer c (representing a Unicode code point), it converts it to a char using the casting operation (char) c.

Putting it all together, the expression inputString.chars().mapToObj(c -> (char) c) converts each character in the input string into a char and represents them as objects in a Stream<Character>.

Stream<Character> charStream = codePoints.mapToObj(c -> (char) c);

For example, if inputString is "abc", the result of this operation would be a stream of characters: ['a', 'b', 'c']. This allows you to perform further stream operations on the characters in the string using the rich set of functions provided by the Stream API in Java.

3. .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())): Groups the characters by their identity (themselves) and counts the occurrences using Collectors.counting().

4. The result is a Map<Character, Long> containing the frequency of each character.

check below example with stepwise breakdown:-

package com.neesri.sameprogrammes;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class FrequencyOfChar {

public static void main(String[] args) {

// in this have to find out frequency of each chars for given string

String inpuString = "i love my country ";

// 1. convert string into IntStream by calling chars on string
// , here removing space by replaceAll method
IntStream intStream = inpuString.replaceAll("\\s", "").chars();

// 2. convert IntSteram into Character Stream by mapToObj(c -> (char) c)
Stream<Character> charWrapperStream = intStream.mapToObj(c -> (char) c);

//3. using groupingby find char and frquency in map
Map<Character, Long> findFrequncyOfChar = charWrapperStream
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

// 4. Displaying the frequency of each character

findFrequncyOfChar.forEach((character,freqency)->
System.out.println("chracter "+character +"freqency "+freqency));
// or
System.out.println(findFrequncyOfChar);




}

}

OR — — — another way — — — — — — — -

String String2 = "i Love My Country India";
Map<String, Long> frequencyMap2 = Arrays.stream(String2.split(""))
.filter(s -> !s.isEmpty() && !s.equals(" "))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

System.out.println(frequencyMap2);

output- { =4, a=3, c=1, C=1, D=1, e=2, f=1, h=1, J=1, n=1, O=1, o=1, p=1, T=1, t=1, v=1, y=1}

OR — — — another way — — removing space and convert to lower case——

String String2 = "i Love My Country India";
Map<String, Long> frequencyMap2 = Arrays.stream(String2.split(""))
.filter(s -> !s.isEmpty() && !s.equals(" "))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

System.out.println(frequencyMap2);
output- {a=1, C=1, d=1, e=1, I=1, i=2, L=1, M=1, n=2, o=2, r=1, t=1, u=1, v=1, y=2}

🔴8. Java 8 program to check if two strings are anagrams or not?

Two strings are said to be anagram if we can form one string by arranging the characters of another string. For example, Race and Care.

Here are a few examples to illustrate the concept of anagrams:

  • “listen” and “silent” are anagrams because you can rearrange the letters to form each other.
  • “triangle” and “integral” are anagrams.
  • “debit card” and “bad credit” are anagrams.
  • “astronomer” and “moon starer” are anagrams.

In anagrams, the order of the characters is changed, but the set of characters remains the same. Anagrams are often used as wordplay or puzzles, and they provide an interesting way to explore the permutations of letters in a word or phrase.

see the program

package com.neesri.sameprogrammes;

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

public class Anagrams {

public static void main(String[] args) {

String string1 = "Heart";
String string2 = "Earth";

string1 = Stream.of(string1.split("")).map(String::toUpperCase)
.sorted().collect(Collectors.joining());
string2 = Arrays.stream(string2.split("")).map(String::toUpperCase)
.sorted().collect(Collectors.joining());

if (string1.equalsIgnoreCase(string2)) {

System.out.println("Two String " + string1 + " and "
+ string2 + " are Anagrams");

} else {
System.out.println("Two String " + string1 +
" and " + string2 + " are NOT Anagrams");

}
}

}

now check step by step explanation — — —

  1. Splitting into Array of Characters:
  • string1.split(""): Splits the string "Heart" into an array of strings where each element represents a single character. The result is ["H", "e", "a", "r", "t"].
  • string2.split(""): Splits the string "Earth" into an array of strings, resulting in ["E", "a", "r", "t", "h"].

2. Converting to Uppercase:

  • .map(String::toUpperCase): Maps each element of the array to its uppercase equivalent.
  • For string1, after mapping, the array becomes ["H", "E", "A", "R", "T"].
  • For string2, after mapping, the array becomes ["E", "A", "R", "T", "H"].

3. Sorting the Characters:

  • .sorted(): Sorts the elements of the array in their natural order (lexicographical order for strings).
  • After sorting, the arrays become ["A", "E", "H", "R", "T"] for both string1 and string2.

4. Joining Characters into a String:

  • .collect(Collectors.joining()): Collects the sorted characters and joins them into a single string.
  • For string1, the result becomes “AEHRT”.
  • For string2, the result also becomes “AEHRT”.

The final values of string1 and string2 are now the sorted and uppercase versions of the original strings. In this specific case, both "Heart" and "Earth" result in the same string "AEHRT" after the processing steps. This makes them anagrams because their characters, when rearranged, form the same string.

🔴9. Find Second last element of an array

 List<String> list11 = Arrays.asList("a", "d", "f", "z", "a");

String secondLast = list11.stream() // Create a Stream from the list11
.skip(list11.size() - 2) // Skip all elements except the second-last one
.findFirst() // Find the first element in the stream
.get(); // Get the value from the Optional<String>

System.out.println(secondLast); // Print the second-last element of the list11

//----OUTPUT---//
Z

🔴10. Find the last element from an integer array.

int[] intArray = {2, 4, 6, 7, 9, 2};
int num = IntStream.of(intArray) // Create an IntStream from the intArray
.skip(intArray.length - 1) // Skip all elements except the last one
.boxed() // Convert the primitive stream to a Stream<Integer>
.findFirst() // Find the first element in the stream
.get(); // Get the value from the Optional<Integer>
System.out.println(num); // Print the last element of the intArray

//---- OUTPUT----//
2

In this code:

  • IntStream.of(intArray) creates an IntStream from the intArray.
  • .skip(intArray.length - 1) skips all elements except the last one.
  • .boxed() converts the IntStream to a Stream<Integer>.
  • .findFirst() finds the first element in the stream, which is the last element of the original array.
  • .get() retrieves the value from the Optional<Integer>.
  • System.out.println(num) prints the last element of the intArray, which is 2 in this case.

So, the output of this code will be 2, which is the last element of the intArray

we can also write this code without using boxed(), so in that case findFirst will return Optionalint() incase of primitive array so we can use getAsInt().


int [] intArray= {2,4,6,7,9,2};
int num= IntStream.of(intArray).skip(intArray.length-1)
.findFirst().getAsInt();
System.out.println(num);

Below is the given code snippet broken down into smaller parts with comments explaining each step:

// Define the integer array
int[] intArray = {2, 4, 6, 7, 9, 2};

// Create an IntStream from the intArray
IntStream intStream = IntStream.of(intArray);

// Skip all elements except the last one
IntStream skippedStream = intStream.skip(intArray.length - 1);

// Find the first element in the stream
OptionalInt optionalInt = skippedStream.findFirst();

// Get the value as an int from the OptionalInt
int num = optionalInt.getAsInt();

// Print the last element of the intArray
System.out.println(num);

🔴11. Find maximum and minimum from list of intergers and also from primitvie Array.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;

public class Main {
public static void main(String[] args) {
List<Integer> listOfIntegers = Arrays.asList(2, 4, 6, 1, 8);

int[] array11 = {2, 4, 6, 1, 8};

// Using listOfIntegers
int maxFromList = listOfIntegers.stream()
.max(Comparator.naturalOrder())
.get();
System.out.println("Max from listOfIntegers: " + maxFromList); // Output: Max from listOfIntegers: 8

// Using IntStream
int maxFromArray = IntStream.of(array11)
.max()
.getAsInt();
System.out.println("Max from array11: " + maxFromArray); // Output: Max from array11: 8
}
}

Key Differences:

  • Data Type: The first snippet operates on a stream of Integer objects, while the second snippet operates on a primitive int stream.
  • Usage of Comparator: In the first snippet, you have the flexibility to specify a custom comparator using max(Comparator), while the second snippet uses natural ordering by default.
  • Retrieval of Result: The first snippet retrieves the maximum value as an Integer object from the Optional<Integer> using get(), while the second snippet retrieves the maximum value as a primitive int using getAsInt() from the OptionalInt.

In summary, the two snippets achieve similar results, but they handle different data types and offer slightly different levels of flexibility in terms of comparison mechanisms.

🔴12. make cube on list elements and filter numbers greater than 50

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

public class CubeFilter {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6);
List<Integer> result = numbers.stream()
.map(n -> n * n * n)
.filter(n -> n > 50)
.collect(Collectors.toList());
System.out.println(result);
}
}
//--------OUTPUT---------
[64, 125, 216]

In this example:

  • numbers.stream() creates a stream from the list of numbers.
  • .map(n -> n * n * n) cubes each element in the stream.
  • .filter(n -> n > 50) filters the cubed values, retaining only those greater than 50.
  • .collect(Collectors.toList()) collects the filtered values into a new list.

🔴13. Print nos that starts with 1 from the list

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

public class StartsWithOne {
public static void main(String[] args) {
//-1----------- For Integer list
List<Integer> numbers =
Arrays.asList(10, 12, 23, 34, 45, 51, 13, 16);
numbers.stream()
.map(String::valueOf)
.filter(s -> s.startsWith("1"))
.forEach(System.out::println);

//--2A-------------- For int Array using Arrays.stream
int[] arr = {10, 12, 23, 34, 45, 51, 13, 16};
Arrays.stream(arr)
.mapToObj(s -> s + "")
.filter(s -> s.startsWith("1"))
.forEach(System.out::println);
//--2B---------------For int Array using InStream.of
IntStream.of(arr).mapToObj(Integer::toString)
.filter(str-> str.startsWith("1"))
.forEach(System.out::println);

}
}
//-----Output-----
10
12
13
16

In this example (For Integer list) :

  • numbers.stream() creates a stream from the list of numbers.
  • .map(String::valueOf) converts each number to its string representation.
  • .filter(s -> s.startsWith("1")) filters the strings, retaining only those that start with '1'.
  • .forEach(System.out::println) prints each filtered string to the console.

In this example (For int Array) :

  • Initial Stream: Arrays.stream(arr) creates a stream from the array arr.
  • Mapping to Strings: .mapToObj(s -> s + "") converts each element of the stream to its string representation.Uses a lambda expression to concatenate the integer with an empty string. It is flexible but might be less efficient.
  • mapToObj(Integer::toString): Uses a method reference to the toString method of the Integer class. It is more efficient and concise.
  • Filtering: .filter(s -> s.startsWith("1")) retains only the strings that start with "1".

🔴13. How to convert a string into a map of key-value pairs using Java 8.

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class KeyValueExample {
public static void main(String[] args) {
String s = "neeraj : Srivastava,raj:sri,akash:sen";

// Convert the string into a map of key-value pairs
Map<String, String> keyValueMap = Arrays.stream(s.split(","))
.map(entry -> entry.split(":"))
.collect(Collectors.toMap(
entry -> entry[0].trim(), // Trim and use the first part as the key
entry -> entry[1].trim() // Trim and use the second part as the value
));

// Print the map
keyValueMap.forEach((key, value) ->
System.out.println(key + " -> " + value));
}
}

Explanation :

  1. Splitting the String:

Arrays.stream(s.split(“,”)) — This splits the string s into individual key-value pairs using the comma , as the delimiter and creates a stream from the resulting array.

2.Mapping to Key-Value Pairs:

.map(entry -> entry.split(“:”)) — This splits each key-value pair using the colon : as the delimiter. The split(":") method returns an array where the first element is the key and the second element is the value.

3.Trimming and Collecting into a Map:

.collect(Collectors.toMap(
entry -> entry[0].trim(), // Key
entry -> entry[1].trim() // Value
))

This collects the stream elements into a Map. The key is the trimmed first element of the array (before the colon), and the value is the trimmed second element of the array (after the colon).

Handling Edge Cases

A.Invalid Format: If the input string doesn’t strictly follow the key:value format, you should add validation.

If the input string might contain malformed entries (e.g., missing keys or values), you might want to add additional checks. Here’s an enhanced version with basic error handling:

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class KeyValueExample {
public static void main(String[] args) {
String s = "neeraj : Srivastava,raj:sri,akash:sen,invalidEntry";

// Convert the string into a map of key-value pairs with basic error handling
Map<String, String> keyValueMap = Arrays.stream(s.split(","))
.map(entry -> entry.split(":"))
.filter(entry -> entry.length == 2) // Filter out malformed entries
.collect(Collectors.toMap(
entry -> entry[0].trim(), // Key
entry -> entry[1].trim() // Value
));

// Print the map
keyValueMap.forEach((key, value)
-> System.out.println(key + " -> " + value));
}
}

This version includes a .filter(entry -> entry.length == 2) to ensure only properly formed key-value pairs are included in the final map.

B.Duplicate Keys: If there are duplicate keys in the input string, the Collectors.toMap method will throw an IllegalStateException. You can handle this by providing a merge function.

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class StringToMapExample {
public static void main(String[] args) {
String s = "neeraj:Srivastava,raj:sri,akash:sen,raj:sam";

Map<String, String> keyValueMap1 = Arrays.stream(s1.split(","))
.map(entry -> entry.split(":"))
.filter(entry -> entry.length == 2) // Filter out malformed entries
.collect(Collectors.toMap(
entry -> entry[0].trim(), // Key
entry -> entry[1].trim(), (e1,e2)->e1 // Value
));

// Print the map
keyValueMap1.forEach((key, value) -> System.out.println(key + " -> " + value));
}
}

In this version, the merge function (e1,e2)->e1 ensures that the first encountered value for a key is retained if there are duplicates.

🔴14. Word Count in reverse order

sort the results by the count in descending order (and by the word in ascending order if counts are equal)

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

public class WordCountExample {
public static void main(String[] args) {
String str = "hello world hello java hello stream java world";

Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(
Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet()
.stream()
.sorted(
Map.Entry.<String, Long>comparingByValue(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey()))
.forEach(entry
-> System.out.println(entry.getKey() + " : " + entry.getValue()));
}
}
//----OUTPUT-----//
hello : 3
java : 2
world : 2
stream : 1

Detailed Steps:

  1. Stream Creation: Convert the input string to a stream of words.
  2. Grouping and Counting: Use Collectors.groupingBy with Function.identity() to count the occurrences of each word and store them in a LinkedHashMap to maintain the order.
  3. Sorting: Sort the map entries by count in descending order. If two words have the same count, they are sorted by their natural order (alphabetically).
  4. Printing: Print the sorted entries.

🔴Separate Odd and Even Numbers from a List of Characters (Without filter())?

Given a list of characters (List<Character>), where each character represents a digit ('0' to '9').

  • Separate odd and even numbers without using .filter().
  • Return the result in a Map<Boolean, List<Integer>> where:
  • true → contains even numbers
  • false → contains odd numbers
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SeparateOddEven {
public static void main(String[] args) {
List<Character> charList = Arrays.asList('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');

// Collecting into Map<Boolean, List<Integer>> without using filter()
Map<Boolean, List<Integer>> separatedNumbers =
charList.stream()
.collect(Collectors.partitioningBy(
c -> (c - '0') % 2 == 0, // Key: Even (true) / Odd (false)
Collectors.mapping(c -> c - '0', Collectors.toList())
// Convert char to Integer
));

// Printing Result
System.out.println("Even Numbers: " + separatedNumbers.get(true));
System.out.println("Odd Numbers: " + separatedNumbers.get(false));
}
}
//----OUTPUT---//
Even Numbers: [2, 4, 6, 8, 0]
Odd Numbers: [1, 3, 5, 7, 9]

— — — — — — Another Way — — — — - -

Instead of using partitioningBy(), we can use groupingBy() with a custom classifier to separate even and odd numbers.

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

public class SeparateOddEven {
public static void main(String[] args) {
List<Character> charList = Arrays.asList('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');

// Grouping even and odd numbers
Map<Boolean, List<Integer>> separatedNumbers = charList.stream()
.collect(Collectors.groupingBy(
c -> (c - '0') % 2 == 0, // Key: true (even), false (odd)
Collectors.mapping(c -> c - '0', Collectors.toList()) // Convert char to int
));

// Printing Result
System.out.println("Even Numbers: " + separatedNumbers.get(true));
System.out.println("Odd Numbers: " + separatedNumbers.get(false));
}
}
//----OUTPUT---//
Even Numbers: [2, 4, 6, 8, 0]
Odd Numbers: [1, 3, 5, 7, 9]
//-- Efficient (O(n) time complexity)---//

🔴15. How do you find frequency of each character in a string using Java 8 streams on order of their occurrences? <check sr no.-7 >

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CharacterFrequencyExample {
public static void main(String[] args) {
String str = "hello world";

// Convert the string to a stream of characters and count their frequency
Map<Character, Long> charFrequency =
str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()));

// Print the character frequencies in order of their occurrences
charFrequency.forEach(
(key, value) -> System.out.println(key + " : " + value));
}
}
output----> :
h : 1
e : 1
l : 3
o : 2
: 1
w : 1
r : 1
d : 1

Explanation:

  1. Convert the String to a Stream of Characters:
  • str.chars() converts the string to an IntStream of character codes.
  • .mapToObj(c -> (char) c) converts each character code to a Character object.

2. Group by Character and Count Frequencies:

.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())) groups the characters by their identity, counts their occurrences, and stores the results in a LinkedHashMap to maintain the insertion order.

3. Print the Character Frequencies:

  • charFrequency.forEach((key, value) -> System.out.println(key + " : " + value)) prints each character and its frequency.

// — — in another way using split----------------------//

you can also use split to convert the string into an array of characters and then use streams to count the frequency of each character while preserving their order. Here’s how you can do it:

  1. Convert the string into an array of characters using split.
  2. Create a stream from the array.
  3. Collect the characters into a LinkedHashMap while counting their occurrences.
  4. Print the map to display the character frequencies in the order they first appear in the string.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CharacterFrequencyExample {
public static void main(String[] args) {
String str = "hello world";

// Convert the string to an array of characters using split and create a
// stream
Map<String, Long> charFrequency =
Stream.of(str.split(""))
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()));

// Print the character frequencies in order of their occurrences
charFrequency.forEach(
(key, value) -> System.out.println(key + " : " + value));
}
}
output-->
h : 1
e : 1
l : 3
o : 2
: 1
w : 1
r : 1
d : 1

This code effectively counts and displays the frequency of each character while preserving the order of their occurrences in the original string.

Explanation:

  1. Convert the String to an Array of Characters:

str.split("") splits the string into an array of single-character strings.

2. Create a Stream from the Array:

Stream.of(str.split("")) creates a stream from the array of single-character strings.

3. Group by Character and Count Frequencies:

.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())) groups the characters by their identity, counts their occurrences, and stores the results in a LinkedHashMap to maintain the insertion order.

4. Print the Character Frequencies:

  • charFrequency.forEach((key, value) -> System.out.println(key + " : " + value)) prints each character and its frequency.

🔴16. Find the frequency of each character in a string, sorting the results in alphabetical order, and returning the map?

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CharacterFrequencyExample {
public static void main(String[] args) {
String str = "hello world";

// Single line to find frequency and sort in alphabetical order
Map<String, Long> charFrequency =
Arrays.stream(str.split(""))
.collect(Collectors.groupingBy(
Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));

System.out.println(charFrequency);
}
}

//--- output--->
: 1
d : 1
e : 1
h : 1
l : 3
o : 2
r : 1
w : 1

Explanation:

  1. Convert to Stream of Characters:

Arrays.stream(str.split("")) splits the string into an array of single-character strings and converts it to a stream.

2. Group and Count Frequencies:

.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) groups the characters by their identity and counts their occurrences.

3. Sort Entries Alphabetically:

.entrySet().stream().sorted(Map.Entry.comparingByKey()) converts the map entries to a stream and sorts them by key (character) in alphabetical order.

4. Collect into a LinkedHashMap:

🔴Find Character Frequency at Even Positions Using Java 8 Streams

Problem Statement:

  1. Given a string, find the frequency of each character present at even indices (0-based indexing).
  2. Filter out characters whose frequency is greater than 2.
  3. Use Java 8 Streams to achieve this.
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class EvenIndexCharFrequency {
public static void main(String[] args) {
String input = "aabbccddeeffggg"; // Example input

// Find frequency of characters at even indices & filter out those with frequency > 2
Map<Character, Long> charFrequency = IntStream.range(0, input.length())
.filter(i -> i % 2 == 0) // Select only even index positions
.mapToObj(input::charAt) // Convert index to character
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) // Count frequency
.entrySet().stream() // Convert Map to Stream for filtering
.filter(entry -> entry.getValue() <= 2) // Remove characters with frequency > 2
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); // Convert back to Map

// Print the result
System.out.println("Character Frequency at Even Positions (Filtered): " + charFrequency);
}
}

🔹 Example Execution

Input
"aabbccddeeffggg"

Character Positions:
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Chars: a a b b c c d d e e f f g g g
Even Index Chars: a, b, c, d, e, f, g, g

Frequency Count at Even Indices:
a = 1, b = 1, c = 1, d = 1, e = 1, f = 1, g = 2

Filtered Output (Only Frequencies ≤ 2):
{a=1, b=1, c=1, d=1, e=1, f=1, g=2}

🔴Get the Next Sunday from Today Using java.time (Java 8)

Problem Statement:

Write a function that returns the date of the next Sunday from today using Java 8’s java.time API.

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class NextSundayFinder {
public static void main(String[] args) {
System.out.println("Next Sunday is on: " + getNextSunday());
}

public static LocalDate getNextSunday() {
return LocalDate.now()
.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
}
}

🔹 Explanation (Step-by-Step)

1️⃣ Get today’s date using LocalDate.now().
2️⃣ Find the next Sunday using .with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).
3️⃣ Return the computed LocalDate.

Next Sunday is on: 2025-02-16

✅ If today is already Sunday, it will return the next Sunday (not today’s date).

— —Another Way —Optimized way using Stream.iterate() ——

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.stream.Stream;

public class NextSundayOptimized {
public static void main(String[] args) {
System.out.println("Next Sunday is on: " + getNextSunday());
}

public static LocalDate getNextSunday() {
return Stream.iterate(LocalDate.now().plusDays(1), date -> date.plusDays(1)) // Start from tomorrow
.filter(date -> date.getDayOfWeek() == DayOfWeek.SUNDAY) // Find the next Sunday
.findFirst() // Stop when the first match is found
.orElse(LocalDate.now().plusDays(7)); // Fallback case (never needed)
}
}

🔹 Step-by-Step Explanation

1️⃣ Generate Future Dates Using Stream.iterate()

Stream.iterate(LocalDate.now().plusDays(1), date -> date.plusDays(1))

LocalDate.now().plusDays(1) → Starts from tomorrow instead of today.
date -> date.plusDays(1) → Keeps adding one day at a time, generating a continuous stream of dates.

💡 Why start from tomorrow?

  • If today is already Sunday, we need the next Sunday (not today).
  • This ensures we don’t mistakenly return today’s date.

2️⃣ Find the First Sunday

.filter(date -> date.getDayOfWeek() == DayOfWeek.SUNDAY)

Keeps only dates that are Sundays.
Filters out all other days of the week.

💡 How does it work?

  • The stream generates Monday → Tuesday → Wednesday … until it finds a Sunday.
  • Once a Sunday is found, it passes the filter and continues to the next step.

3️⃣ Stop When a Match is Found

.findFirst()

Stops execution immediately once the first Sunday is found.
Prevents unnecessary iterations, making it more efficient.

💡 Why use .findFirst()?

  • Without it, the stream would keep generating dates infinitely.
  • .findFirst() stops as soon as it finds the first Sunday, improving performance.

4️⃣ Handle Edge Cases Using .orElse()

.orElse(LocalDate.now().plusDays(7))

Ensures a fallback value (though this case will never occur).
Why LocalDate.now().plusDays(7)?

  • If somehow no Sunday is found (which is impossible), it defaults to the next week.
  • In Java 8, we use .orElse() instead of .orElseThrow() (Java 10 feature).

🔴17. How to merge two unsorted arrays?

🔴17. How to merge two unsorted arrays?

package com.neesri.sameprogrammes;

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

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

IntStream instream1 = IntStream.of(array1);
IntStream insstream2 = Arrays.stream(array2);

int[] c =IntStream.concat(instream1, insstream2)
.sorted().distinct().toArray();

System.out.println(Arrays.toString(c));
}
}
//--------output -->
[1, 3, 4, 5, 6, 7, 8, 9]

🔴18.Given a list of integers, separate odd and even numbers?

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

public class Java8Code {
public static void main(String[] args) {

List<Integer> listOfIntegers =
Arrays.asList(5, 12, 33, 48, 59, 62, 74, 83, 96, 101);

// Partitioning the numbers into odd and even
Map<Boolean, List<Integer>> oddEvenNumbersMap =
listOfIntegers.stream().collect(
Collectors.partitioningBy(i -> i % 2 == 0));

// Iterating over the entry set
oddEvenNumbersMap.forEach((isEven, numbers) -> {
System.out.println("--------------");
System.out.println(isEven ? "Even Numbers" : "Odd Numbers");
System.out.println("--------------");
numbers.forEach(System.out::println);
});
}
}

//----------OUTPUT---------------
--------------
Odd Numbers
--------------
5
33
59
83
101
--------------
Even Numbers
--------------
12
48
62
74
96

🔴19. Check if a Number is Fibonacci (Using Streams)

import java.util.stream.Stream;

public class FibonacciCheck {
public static void main(String[] args) {
int num = 21;

boolean isFibonacci =
Stream.iterate(new int[]{0, 1},
f -> new int[]{f[1], f[0] + f[1]})
.map(f -> f[0])
.limit(20) // Limit the sequence (adjust as needed)
.anyMatch(x -> x == num);

System.out.println(num + " is Fibonacci? " + isFibonacci);
}
}
//----OUTPUT---//

21 is Fibonacci? true

🔴20.Sum of First N Fibonacci Numbers

import java.util.stream.Stream;

public class FibonacciSum {
public static void main(String[] args) {
int n = 10;

int sum = Stream.iterate(new int[]{0, 1},
f -> new int[]{f[1], f[0] + f[1]})
.limit(n)
.mapToInt(f -> f[0])
.sum();

System.out.println("Sum of First " + n +
" Fibonacci Numbers: " + sum);
}
}

//----OUTPUT----//

Sum of First 10 Fibonacci Numbers: 88

Thanks & Happy Learning :)

--

--

Responses (3)