- Java 8 coding interview questions(Basic)
- 1. Java 8 Program to add prefix and suffix to the String?
- 2. Java 8 Program to Print ten random numbers using forEach?
- 3. Java 8 program to iterate a Stream using the forEach method?
- 4. Java 8 program to find the Minimum number of a Stream?
- 5. Java 8 program to find the Maximum number of a Stream?
- 6. Java 8 program to Count Strings whose length is greater than 3 in List?
- 7. Java 8 program to Print Strings whose length is greater than 3 in List.
- 8. Java 8 program to multiply 3 to all elements in the list and print the list?
- 9. Java 8 program to perform concatenation on two Streams?
- 10. Java 8 program to remove the duplicate elements from the list?
- 11. Print current date and time in Java 8 Date and Time API?
- 12. Java 8 program to Sort the given list?
- 13. Write a Java 8 program to get the sum of all numbers present in a list.
- 14. Java 8 program to perform cube on list elements and filter numbers greater than 50.
- Some Advance Java 8 Coding Question Starting from here
- 15. Filter and sum even numbers in a list using Streams.
- 16. Convert a List<String> to a Map<String, Integer>where Integer of the map will be the length of String.
- 17. Separate odd and even numbers into two lists using Java 8.
- 18. Find character frequency in a String using Streams.
- 19. Merge two Integer arrays into one sorted array (optionally removing duplicates).
- 20. Get top 3 maximum & minimum numbers from a list using Streams.
- 21. Find the second largest number in an integer array.
- 22. Check if two strings are anagrams using Streams.
- 23. Reverse each word in a sentence using Streams.
- 24. Print first duplicate characters in a String with Streams.
- 25. Generate Fibonacci series with Streams.
- 26. Filtering and squaring odd numbers from 1 to 10 (filter + map).
- 27. Extract unique words from a list of sentences (flatMap + split).
- 28. Implement a custom Collector, e.g., concatenating strings with a delimiter.
- 29. Find sum of even and odd Java 8.
- 30. finds the 5th smallest distinct number from the numbers list.
- 31. Find the first non-repeated character in it using Stream functions.
- 32. Sort a given Map using Java 8.
This post was designed and prepared with one clear intention that is to help students and job seekers who often struggle to find authentic and practical Java 8 coding questions that actually asked during the interviewers in real interviews.
If you’ve ever opened a blog expecting something new, only to see the same repetitive questions again and again then you’re not alone. That exact frustration is what led Prakash Kumar to take a different path.
After attending 50+ interviews across top MNCs like TCS, Infosys, Cognizant, Wipro, IBM, Accenture, Capgemini, and even product companies like Amazon and Oracle, he personally curated this list based on real experience not theory.
After going through each questions mentioned on this blog, you will confidently answer the coding question from the java 8 topics like Streams, Lambda Expressions, Functional Interfaces, Method References, and Optional.
If you’re still working with older versions of Java, now is the time to practice Java 8-specific problems and adapt to the new standards. Interviewers today are keen to test your understanding of Java 8 through real-world coding scenarios.
🔍 This set of questions is designed to help you prepare for both beginner and advanced levels, making it easier to tackle Java 8-based coding rounds confidently.
To take your preparation even deeper, make sure to check out:
🔗 Java 8 Scenario-Based Questions Using Employee Class — highly practical for object-based coding interviews.
🔗 Java 8 Real-World Scenario Coding Questions — a perfect list if you’re aiming to stand out in the logic round.
💬 Every question here is included with purpose, designed to strengthen your understanding and give you an edge over others who are just “reading without practicing.”
❤️ If you find this helpful, please share it with your friends, bookmark it for revision, and help others who are on the same journey. Sometimes, one good resource is all it takes to crack your dream job.
Java 8 coding interview questions(Basic)
You can scroll down to directly go the some advanced Java Interview Questions below.
1. Java 8 Program to add prefix and suffix to the String?
To write a program in java to add prefix and suffix in a given String we will use StringJoiner class, a newly added in Java 8. In the below program We will be adding “#“ and “#” as a prefix and suffix in the string.
Program
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
StringJoiner stringJoiner = new StringJoiner(",", "#", "#");
stringJoiner.add("Interview");
stringJoiner.add("Questions");
stringJoiner.add("Answers");
System.out.println("String after adding # in suffix and prefix :");
System.out.println(stringJoiner);
}
}
Output
String after adding # in suffix and prefix :
#Interview,Questions,Answers#
2. Java 8 Program to Print ten random numbers using forEach?
Below is the program to generate 10 random number using forEach. Here we are using a Random class to generate Random number.
Program
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
}
}
Output
2095408578
-489399752
36994816
-2142661
-205103943
-93934163
-1884588823
-373986104
-909012198
1134601393
3. Java 8 program to iterate a Stream using the forEach method?
In the below program, we have created a List of array types. And We are iterating this using forEach after converting into the stream.
Program
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> str = Arrays.asList("Hello","Interview","Questions","Answers");
str.stream().forEach(System.out::println);
}
}
Output
Hello
Interview
Questions
Answers
4. Java 8 program to find the Minimum number of a Stream?
We are using comparator.comparing() method which will take integer value from Stream.
Program 1: Using Comparator.comparing()
This is valid when arr is of type Integer.
import java.util.Comparator;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Integer min = Stream.of(1, 2, 3, 4, 5, 6,7)
.min(Comparator.comparing(Integer::valueOf))
.get();
System.out.println("The Minimum number is: " + min);
}
}
Output
The Minimum number is: 1
Program 2: Using min() with getAsInt() function
This is valid when arr is of type int.
import java.util.*;
class Main{
public static void main(String[] args) {
int arr[] = {1,2,3,4,5};
int min = Arrays.stream(arr).min().getAsInt();
System.out.println(min);
}
}
Output
The Minimum number is: 1
5. Java 8 program to find the Maximum number of a Stream?
To find the Maximum number in the stream, we will use comparator.comparing() method which will take integer value from Stream.
Below is the program to find Maximum in Stream.
Program 1: Using Comparator.comparing()
This is valid when arr is of type Integer.
import java.util.Comparator;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Integer max = Stream.of(1, 2, 3, 4, 5, 6,7)
.max(Comparator.comparing(Integer::valueOf))
.get();
System.out.println("The Maximum number is: " + max);
}
}
Output
The Maximum number is: 7
Program 2: Using max() function with getAsInt()
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6,7};
int max = Arrays.stream(arr).max().getAsInt();
System.out.println("The Maximum number is: " + max); // Output: 7
}
}
Output
The Maximum number is: 7
6. Java 8 program to Count Strings whose length is greater than 3 in List?
In the below program we will be using filter and count function of java 8 to identify the string whose length is greater than 3.
Program
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> stringList = Arrays.asList("Hello","Interview","Questions","Answers","Ram","for");
long count = stringList.stream().filter(str -> str.length() > 3).count();
System.out.println("String count with greater than 3 digit : " + count);
}
}
Output
String count with greater than 3 digit : 4
7. Java 8 program to Print Strings whose length is greater than 3 in List.
Program
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> stringList = Arrays.asList("Hello","Interview","Questions","Answers","Ram","for");
stringList.stream().filter(str -> str.length() > 3).forEach(System.out::println);
}
}
Output
Hello
Interview
Questions
Answers
8. Java 8 program to multiply 3 to all elements in the list and print the list?
To perform a multiply of 3 on each element of the list we will use the map() function. This function will perform the operation and will generate a new stream with an updated value.
Program
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7);
System.out.println(integerList.stream().map(i -> i*3).collect(Collectors.toList()));
}
}
Output
[3, 6, 9, 12, 15, 18, 21]
9. Java 8 program to perform concatenation on two Streams?
To Perform concatenation on two stream, first we will create two streams and using the concat function we will perform string concatenation.
Program
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> integerList1 = Arrays.asList(1,2,3,4);
List<Integer> integerList2 = Arrays.asList(5,6,7);
Stream<Integer> concatStream = Stream.concat(integerList1.stream(), integerList2.stream());
concatStream.forEach(System.out::print);
}
}
Output
1234567
10. Java 8 program to remove the duplicate elements from the list?
To remove duplicate element form list we have used Collectors.toSet(). As we know that set can have only unique value, we are converting our list to set so that we can have only unique value.
Program 1: Using Collectors.toSet()
import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(1,2,3,4,1,2,3);
System.out.println("After removing duplicates : ");
integerList.stream().collect(Collectors.toSet()).forEach(System.out::print);
}
}
Output
After removing duplicates :
1234
Program 2: Using distinct()
import java.util.*;
import java.util.stream.*;
public class Main
{
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(
Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5));
list.stream().distinct().collect(Collectors.toList()).forEach(System.out::println);;
}
}
Output
1
10
2
3
4
5
11. Print current date and time in Java 8 Date and Time API?
To get the current date and time we are using LocalDate, LocalTime, and LocalDateTime API provided in Java 8.
Program
public class Main {
public static void main(String[] args) {
System.out.println("Current Date: " + java.time.LocalDate.now());
System.out.println("Current Time: " + java.time.LocalTime.now());
System.out.println("Current Date and Time: " + java.time.LocalDateTime.now());
}
}
Output
Current Date: 2023-07-06
Current Time: 13:18:05.516980
Current Date and Time: 2023-07-06T13:18:05.517781
12. Java 8 program to Sort the given list?
To Sort the integer element given in List, we will use the sorted() method which will sort the List elements.
Program
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(4,5,6,7,1,2,3);
integerList.stream().sorted().forEach(System.out::println);
}
}
Output
1
2
3
4
5
6
7
13. Write a Java 8 program to get the sum of all numbers present in a list.
Program 1: Using sum()
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(4,5,6,7,1,2,3);
System.out.println("Sum of all numbers: " + integerList.stream().mapToInt(Integer::intValue).sum());
}
}
Output
Sum of all numbers: 28
Program 2: Using reduce()
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(4,5,6,7,1,2,3);
// Using reduce to calculate sum
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println("Sum of all numbers: " + sum);
}
}
Output
Sum of all numbers: 28
14. Java 8 program to perform cube on list elements and filter numbers greater than 50.
Program
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(4,5,6,7,1,2,3);
integerList.stream().map(i -> i*i*i).filter(i -> i>50).forEach(System.out::println);
}
}
Output
64
125
216
343
Some Advance Java 8 Coding Question Starting from here
15. Filter and sum even numbers in a list using Streams.
Program 1: Lambda Expression
import java.util.Arrays;
import java.util.List;
public class FilterAndSum {
public static void main(String ...a){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
// Filter even numbers and calculate their sum
int evenSum = list.stream()
.filter(n -> n % 2 == 0) // filters 2, 4, 6
.mapToInt(n -> n) // converts Integer to int
.sum(); // sums them: 2 + 4 + 6 = 12
System.out.println(evenSum); // Output: 12
}
}
Output
Sum of even number= 12
Program 2: We can also simplify mapToInt(n -> n)
using method reference:
import java.util.Arrays;
import java.util.List;
public class FilterAndSum {
public static void main(String ...a){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
// Filter even numbers and calculate their sum
int evenSum = list.stream()
.filter(n -> n % 2 == 0) // filters 2, 4, 6
.mapToInt(Integer::intValue) // converts Integer to int
.sum(); // sums them: 2 + 4 + 6 = 12
System.out.println(evenSum); // Output: 12
}
}
Output
Sum of even number= 12
16. Convert a List<String> to a Map<String, Integer>where Integer of the map will be the length of String.
Program 1: By character case transformation
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StringListToMap {
public static void main(String ...a){
List<String> list = Arrays.asList("Apple", "banana", "apple", "orange", "banana", "apple");
Map<String,Long> counter = list.stream()
.collect(Collectors.groupingBy(s->s.toLowerCase(),Collectors.counting()));
counter.forEach((k,v)->System.out.println(k+" "+v));
}
}
Output
orange 1
banana 2
apple 3
Program 2: No character case transformation
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.function.Function;
public class StringListToMap {
public static void main(String ...a) {
List<String> list = Arrays.asList("Apple", "banana", "apple", "orange", "banana", "apple");
Map<String,Long> counter = list.stream().collect(Collectors
.groupingBy(Function.identity(),Collectors.counting()));
counter.forEach((k,v)->System.out.println(k+" "+v));
}
}
Output
orange 1
banana 2
apple 2
Apple 1
17. Separate odd and even numbers into two lists using Java 8.
Collectors.partitioningBy(n -> n % 2 == 0)
splits the list into two groups:
true
: even numbersfalse
: odd numbers
Program
import java.util.*;
import java.util.stream.Collectors;
public class SeparateOddEvenList {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 15, 20, 25, 30, 35, 40);
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);
}
}
Output
Even Numbers: [10, 20, 30, 40]
Odd Numbers: [15, 25, 35]
18. Find character frequency in a String using Streams.
Program
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CharFrequency {
public static void main(String[] args) {
String input = "stringfrequencystreamexample";
Map<Character, Long> frequencyMap = input.chars() // returns an IntStream
.mapToObj(c -> (char) c) // convert int to char
.collect(Collectors.groupingBy(
Function.identity(), // group by character
Collectors.counting() // count frequency
));
// Print frequency
System.out.println("Character frequency in string are:");
frequencyMap.forEach((ch, count) ->
System.out.println(ch + " : " + count)
);
}
}
Output
Character frequency in string are:
a : 2
c : 1
e : 5
f : 1
g : 1
i : 1
l : 1
m : 2
n : 2
p : 1
q : 1
r : 3
s : 2
t : 2
u : 1
x : 1
y : 1
19. Merge two Integer arrays into one sorted array (optionally removing duplicates).
Program 1. Merge & Sort (with duplicates)
import java.util.Arrays;
import java.util.stream.Stream;
public class MergeWithDuplicates {
public static void main(String[] args) {
Integer[] arr1 = {3, 5, 7, 9};
Integer[] arr2 = {2, 4, 6, 8};
Integer[] mergedSorted = Stream.concat(Arrays.stream(arr1), Arrays.stream(arr2))
.sorted()
.toArray(Integer[]::new);
System.out.println("Merged with duplicates: " + Arrays.toString(mergedSorted));
}
}
Output
Merged with duplicates: [2, 3, 4, 5, 6, 7, 8, 9]
Program 2. Merge & Sort (without duplicates)
import java.util.Arrays;
import java.util.stream.Stream;
public class MergeWithoutDuplicates {
public static void main(String[] args) {
Integer[] arr1 = {3, 5, 7, 9};
Integer[] arr2 = {3, 4, 6, 9};
Integer[] mergedUniqueSorted = Stream.concat(Arrays.stream(arr1), Arrays.stream(arr2))
.distinct() // remove duplicates
.sorted()
.toArray(Integer[]::new);
System.out.println("Merged without duplicates: " + Arrays.toString(mergedUniqueSorted));
}
}
Output
Merged without duplicates: [3, 4, 5, 6, 7, 9]
Check when given input is int (primitive) not Integer.
20. Get top 3 maximum & minimum numbers from a list using Streams.
Program
import java.util.*;
import java.util.stream.Collectors;
public class Top3MaxMinNum {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(15, 3, 45, 9, 27, 30, 1, 99, 67);
// Top 3 Maximum
List<Integer> top3Max = numbers.stream()
.sorted(Comparator.reverseOrder()) // Sort descending
.limit(3)
.collect(Collectors.toList());
// Top 3 Minimum
List<Integer> top3Min = numbers.stream()
.sorted() // Sort ascending by default
.limit(3)
.collect(Collectors.toList());
System.out.println("Top 3 Maximum Numbers: " + top3Max);
System.out.println("Top 3 Minimum Numbers: " + top3Min);
}
}
Output
Top 3 Maximum Numbers: [99, 67, 45]
Top 3 Minimum Numbers: [1, 3, 9]
21. Find the second largest number in an integer array.
Program 1: Java 8 Code (for int[])
import java.util.Arrays;
public class SecondLargestIntArray {
public static void main(String[] args) {
int[] arr = {10, 20, 35, 40, 50, 35, 50};
Integer secondLargest = Arrays.stream(arr) // IntStream
.distinct() // Remove duplicates
.boxed() // Convert to Stream<Integer>
.sorted((a, b) -> b - a) // Sort descending
.skip(1) // Skip the largest
.findFirst() // Get the second largest
.orElse(null); // Return null if not found
System.out.println("Second Largest: " + secondLargest);
}
}
Output
Second Largest: 40
Program 2: Java 8 Code: Second Largest in Integer[]
If your array is of wrapper type Integer[], then the process becomes slightly simpler since you’re already working with Stream<Integer>
and don’t need to use boxed()
import java.util.Arrays;
public class SecondLargestWrapper {
public static void main(String[] args) {
Integer[] arr = {10, 20, 35, 40, 50, 35, 50};
Integer secondLargest = Arrays.stream(arr)
.distinct() // Remove duplicates
.sorted((a, b) -> b - a) // Sort descending
.skip(1) // Skip the largest
.findFirst() // Get the second largest
.orElse(null); // Handle empty result
System.out.println("Second Largest: " + secondLargest);
}
}
Output
Second Largest: 40
22. Check if two strings are anagrams using Streams.
Program
import java.util.stream.Collectors;
public class AnagramChecker {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
boolean isAnagram = isAnagramUsingStreams(str1, str2);
System.out.println("Are Anagrams? " + isAnagram);
}
public static boolean isAnagramUsingStreams(String s1, String s2) {
if (s1.length() != s2.length()) return false;
// Normalize to lowercase and sort characters
String sorted1 = s1.toLowerCase().chars()
.sorted()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
String sorted2 = s2.toLowerCase().chars()
.sorted()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
return sorted1.equals(sorted2);
}
}
Output
Are Anagrams? true
23. Reverse each word in a sentence using Streams.
Program
import java.util.Arrays;
import java.util.stream.Collectors;
public class ReverseEachWord {
public static void main(String[] args) {
String sentence = "Java 8 Streams are powerful";
String result = Arrays.stream(sentence.split(" "))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
System.out.println("Reversed Words: " + result);
}
}
Output
Reversed Words: avaJ 8 smaertS era lufrewop
24. Print first duplicate characters in a String with Streams.
Program
import java.util.*;
import java.util.stream.*;
public class FirstDuplicateCharacter {
public static void main(String[] args) {
String input = "programming";
Optional<Character> firstDuplicate = input.chars()
.mapToObj(c -> (char) c) // Convert int to char
.collect(Collectors.toMap(
c -> c, // key = character
c -> 1, // value = count (initially 1)
(oldVal, newVal) -> oldVal + 1, // merge counts
LinkedHashMap::new // preserve insertion order
))
.entrySet().stream()
.filter(e -> e.getValue() > 1) // only duplicates
.map(Map.Entry::getKey)
.findFirst();
if (firstDuplicate.isPresent()) {
System.out.println("First duplicate character: " + firstDuplicate.get());
} else {
System.out.println("No duplicate characters found.");
}
}
}
Output
First duplicate character: r
Explanation
input.chars()
→ Returns a stream of character code points..mapToObj(c -> (char) c)
→ Converts toStream<Character>
.Collectors.toMap(...)
withLinkedHashMap::new
maintains insertion order.- After building the frequency map, we:
- Stream through
.entrySet()
- Filter those with count > 1 (duplicates)
- Return the first such character.
- Stream through
25. Generate Fibonacci series with Streams.
Program
import java.util.stream.Stream;
public class FibonacciWithStreams {
public static void main(String[] args) {
int limit = 10; // number of Fibonacci numbers to generate
Stream.iterate(new int[]{0, 1}, pair -> new int[]{pair[1], pair[0] + pair[1]})
.limit(limit)
.map(pair -> pair[0])
.forEach(System.out::println);
}
}
Output
0
1
1
2
3
5
8
13
21
34
Explanation
Stream.iterate(new int[]{0, 1}, ...)
:- Starts from the pair
[0, 1]
- Each next pair is
[current, current + previous]
- Starts from the pair
.map(pair -> pair[0])
:- Extracts the current Fibonacci number
.limit(n)
:- Limits how many numbers to generate
.forEach(System.out::println)
:- Prints each number
26. Filtering and squaring odd numbers from 1 to 10 (filter + map).
Program
import java.util.stream.IntStream;
public class FilterAndSquareOddNumbers {
public static void main(String[] args) {
IntStream.rangeClosed(1, 10) // Stream of numbers 1 to 10
.filter(n -> n % 2 != 0) // Keep only odd numbers
.map(n -> n * n) // Square each odd number
.forEach(System.out::println); // Print each result
}
}
Output
1
9
25
49
81
Explanation
IntStream.rangeClosed(1, 10)
→ Generates numbers from 1 to 10 inclusive..filter(n -> n % 2 != 0)
→ Filters only odd numbers..map(n -> n * n)
→ Squares each filtered number..forEach(...)
→ Prints each squared number.
27. Extract unique words from a list of sentences (flatMap + split).
Program
import java.util.*;
import java.util.stream.Collectors;
public class UniqueWordsExtractor {
public static void main(String[] args) {
List<String> sentences = Arrays.asList(
"Java is powerful",
"Streams are powerful in Java",
"Java 8 introduced streams"
);
Set<String> uniqueWords = sentences.stream()
.flatMap(sentence -> Arrays.stream(sentence.split("\\s+"))) // split by whitespace
.map(String::toLowerCase) // normalize case (optional)
.distinct() // remove duplicates
.collect(Collectors.toSet()); // collect into Set for uniqueness
System.out.println("Unique Words: " + uniqueWords);
}
}
Output
Unique Words: [java, is, powerful, streams, are, in, 8, introduced]
Explanation
flatMap(...)
flattens multiple streams of words into a single stream.split("\\s+")
splits each sentence by one or more spaces.map(String::toLowerCase)
makes comparison case-insensitive.distinct()
orCollectors.toSet()
ensures only unique words are included.
28. Implement a custom Collector, e.g., concatenating strings with a delimiter.
Program
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Stream;
public class CustomCollectorExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
String result = names.stream()
.collect(concatenateWithDelimiter(", "));
System.out.println("Concatenated String: " + result);
}
public static Collector<String, StringBuilder, String> concatenateWithDelimiter(String delimiter) {
return Collector.of(
StringBuilder::new, // supplier
(sb, str) -> {
if (sb.length() > 0) sb.append(delimiter); // accumulator
sb.append(str);
},
(sb1, sb2) -> {
if (sb1.length() > 0 && sb2.length() > 0) sb1.append(delimiter);
sb1.append(sb2);
return sb1;
},
StringBuilder::toString // finisher
);
}
}
Output
Concatenated String: Alice, Bob, Charlie
29. Find sum of even and odd Java 8.
Program 1: Sum of Even and Odd Numbers
import java.util.Arrays;
import java.util.List;
public class SumEvenOdd {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 15, 20, 25, 30, 35);
int evenSum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
int oddSum = numbers.stream()
.filter(n -> n % 2 != 0)
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum of Even Numbers: " + evenSum);
System.out.println("Sum of Odd Numbers: " + oddSum);
}
}
Output
Sum of Even Numbers: 60
Sum of Odd Numbers: 75
Program 2: Single Pass Using Collectors.partitioningBy
import java.util.*;
import java.util.stream.Collectors;
public class SumEvenOdd {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 21, 32, 43, 54, 65);
Map<Boolean, Integer> sumMap = numbers.stream()
.collect(Collectors.partitioningBy(
n -> n % 2 == 0, // true = even, false = odd
Collectors.summingInt(n -> n)
));
int evenSum = sumMap.get(true);
int oddSum = sumMap.get(false);
System.out.println("Sum of Even Numbers: " + evenSum);
System.out.println("Sum of Odd Numbers: " + oddSum);
}
}
Output
Sum of Even Numbers: 96
Sum of Odd Numbers: 129
30. finds the 5th smallest distinct number from the numbers list.
Program
import java.util.*;
import java.util.stream.*;
public class FifthSmallestDistinct {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 5, 3, 5, 8, 2, 10, 12, 7, 2, 6);
Optional<Integer> fifthSmallest = numbers.stream()
.distinct() // remove duplicates
.sorted() // sort ascending
.skip(4) // skip first 4 => 5th element
.findFirst(); // get the 5th smallest
if (fifthSmallest.isPresent()) {
System.out.println("5th Smallest Distinct Number: " + fifthSmallest.get());
} else {
System.out.println("Less than 5 distinct numbers in the list.");
}
}
}
Output
5th Smallest Distinct Number: 7
31. Find the first non-repeated character in it using Stream functions.
Program
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FirstNonRepeatedChar {
public static void main(String[] args) {
String input = "streamsample";
Optional<Character> firstNonRepeated = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(), // group by character
LinkedHashMap::new, // preserve insertion order
Collectors.counting() // count frequency
))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1) // only non-repeated
.map(Map.Entry::getKey)
.findFirst(); // get the first one
if (firstNonRepeated.isPresent()) {
System.out.println("First non-repeated character: " + firstNonRepeated.get());
} else {
System.out.println("No non-repeated characters found.");
}
}
}
Output
First non-repeated character: t
32. Sort a given Map using Java 8.
Given Map
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 1);
map.put("orange", 2);
Program 1: Sort by Keys (Ascending)
Map<String, Integer> sortedByKey = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new // Maintain insertion order
));
System.out.println("Sorted by Key: " + sortedByKey);
Program 2: Sort by Values (Ascending)
Map<String, Integer> sortedByValue = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
System.out.println("Sorted by Value: " + sortedByValue);
Program 3: Sort by Values (Descending)
Map<String, Integer> sortedByValueDesc = map.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
System.out.println("Sorted by Value Desc: " + sortedByValueDesc);
Output
Sorted by Key: {apple=3, banana=1, orange=2}
Sorted by Value: {banana=1, orange=2, apple=3}
Sorted by Value Desc: {apple=3, orange=2, banana=1}