1. Reverse a String
Definition: This program reverses a string manually without using built-in reverse methods.
public class ReverseString {
public static void main(String[] args) {
String str = "Java"; // Original string
char[] arr = str.toCharArray(); // Convert string to character array
int left = 0, right = arr.length - 1;
// Swap characters from start and end moving towards center
while (left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
System.out.println(new String(arr));
// Output: avaJ (Original: Java → Reversed: avaJ)
}
}
2. Find Duplicate Elements in Array
Definition: This program finds elements that appear more than once in an array.
import java.util.*;
public class FindDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 4, 1};
Set<Integer> seen = new HashSet<>(); // Stores unique elements
Set<Integer> duplicates = new HashSet<>(); // Stores duplicate elements
for (int num : arr) {
if (!seen.add(num)) { // add() returns false if element already exists
duplicates.add(num);
}
}
System.out.println(duplicates);
// Output: [1, 2] (These numbers appeared more than once)
}
}
3. First Non-Repeated Character
Definition: This program finds the first character in a string that appears only once.
import java.util.*;
public class FirstNonRepeated {
public static void main(String[] args) {
String str = "aabbcdde";
Map<Character, Integer> map = new LinkedHashMap<>();
// LinkedHashMap maintains insertion order
// Count frequency of each character
for (char c : str.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
// Find first character with frequency 1
for (var entry : map.entrySet()) {
if (entry.getValue() == 1) {
System.out.println(entry.getKey());
break;
}
}
// Output: c (First character that appears only once)
}
}
4. Check if Two Strings Are Anagram
Definition: This program checks whether two strings contain the same characters in different order.
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
char[] a = s1.toCharArray();
char[] b = s2.toCharArray();
Arrays.sort(a); // Sort characters alphabetically
Arrays.sort(b);
System.out.println(Arrays.equals(a, b));
// Output: true (Both contain same characters)
}
}
5. Implement LRU Cache
Definition: This program implements Least Recently Used (LRU) cache which removes the least recently accessed element when capacity is exceeded.
import java.util.*;
class LRUCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
LRUCache(int capacity) {
super(capacity, 0.75f, true);
// true → maintains access order (important for LRU)
this.capacity = capacity;
}
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
// Remove oldest entry if capacity exceeded
}
}
public class TestLRU {
public static void main(String[] args) {
LRUCache<Integer, String> cache = new LRUCache<>(3);
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
cache.get(1); // Access 1 → makes 2 least recently used
cache.put(4, "D"); // Removes 2
System.out.println(cache);
// Output: {3=C, 1=A, 4=D}
// 2 was removed because it was least recently used
}
}
6. Thread-Safe Singleton
Definition: This ensures only one instance of a class is created even in multithreaded environment.
class Singleton {
private static volatile Singleton instance;
// volatile ensures visibility across threads
private Singleton() {} // private constructor
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
7. Producer-Consumer Problem
Definition: One thread produces data while another consumes it using a shared blocking queue.
import java.util.concurrent.*;
public class ProducerConsumer {
public static void main(String[] args) {
BlockingQueue<Integer> queue =
new ArrayBlockingQueue<>(5);
// Capacity = 5
Runnable producer = () -> {
try {
for (int i = 1; i <= 5; i++) {
queue.put(i); // blocks if queue is full
System.out.println("Produced: " + i);
}
} catch (Exception e) {}
};
Runnable consumer = () -> {
try {
for (int i = 1; i <= 5; i++) {
System.out.println("Consumed: " + queue.take());
// blocks if queue is empty
}
} catch (Exception e) {}
};
new Thread(producer).start();
new Thread(consumer).start();
}
/*
Sample Output (order may vary):
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
...
*/
}
8. Detect Cycle in Linked List
Definition: This checks whether a linked list contains a loop using Floyd’s Cycle Detection algorithm.
class Node {
int data;
Node next;
Node(int data) { this.data = data; }
}
public class DetectCycle {
static boolean hasCycle(Node head) {
Node slow = head; // moves 1 step
Node fast = head; // moves 2 steps
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true; // cycle detected
}
return false; // no cycle
}
}
9. Longest Substring Without Repeating Characters
Definition: Finds the length of the longest substring without duplicate characters.
import java.util.*;
public class LongestSubstring {
public static void main(String[] args) {
String s = "abcabcbb";
Set<Character> set = new HashSet<>();
int left = 0, max = 0;
for (int right = 0; right < s.length(); right++) {
// Remove characters until no duplicate
while (!set.add(s.charAt(right))) {
set.remove(s.charAt(left++));
}
max = Math.max(max, right - left + 1);
}
System.out.println(max);
// Output: 3 (Substring: "abc")
}
}
10. Group Anagrams
Definition: Groups words that are rearrangements of each other.
import java.util.*;
public class GroupAnagrams {
public static void main(String[] args) {
String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
Map<String, List<String>> map = new HashMap<>();
for (String word : words) {
char[] chars = word.toCharArray();
Arrays.sort(chars); // Sort letters to create key
String key = new String(chars);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(word);
}
System.out.println(map.values());
/*
Output:
[[eat, tea, ate], [tan, nat], [bat]]
*/
}
}11. Write Your Own Immutable Class
Definition: This class is immutable, meaning its state cannot be changed after object creation.
final class Person {
private final String name; // final → cannot be reassigned
private final List<String> skills; // final reference
public Person(String name, List<String> skills) {
this.name = name;
this.skills = new ArrayList<>(skills);
// defensive copy to prevent external modification
}
public String getName() {
return name;
}
public List<String> getSkills() {
return new ArrayList<>(skills);
// return copy to maintain immutability
}
}
/*
Key Rules of Immutable Class:
1. Class should be final
2. Fields should be private and final
3. No setters
4. Return copies of mutable objects
*/
12. Implement Custom Thread Pool
Definition: This creates a simple thread pool that reuses worker threads to execute submitted tasks.
import java.util.concurrent.*;
class SimpleThreadPool {
private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
// Task queue
public SimpleThreadPool(int nThreads) {
for (int i = 0; i < nThreads; i++) {
new Worker().start(); // Start worker threads
}
}
public void submit(Runnable task) {
queue.offer(task); // Add task to queue
}
class Worker extends Thread {
public void run() {
while (true) {
try {
queue.take().run();
// take() blocks until task available
} catch (Exception ignored) {}
}
}
}
}
13. Design Rate Limiter (Fixed Window)
Definition: Limits the number of requests allowed within a specific time window.
import java.util.concurrent.atomic.AtomicInteger;
class RateLimiter {
private final int limit; // max allowed requests
private final long windowSizeMs; // time window size
private long windowStart;
private AtomicInteger count = new AtomicInteger(0);
public RateLimiter(int limit, long windowSizeMs) {
this.limit = limit;
this.windowSizeMs = windowSizeMs;
this.windowStart = System.currentTimeMillis();
}
public synchronized boolean allowRequest() {
long now = System.currentTimeMillis();
// Reset window if time exceeded
if (now - windowStart > windowSizeMs) {
windowStart = now;
count.set(0);
}
return count.incrementAndGet() <= limit;
}
}
14. Find Kth Largest Element
Definition: Finds the Kth largest element using a Min Heap (PriorityQueue).
import java.util.*;
public class KthLargest {
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
// Min Heap
for (int n : nums) {
pq.offer(n);
if (pq.size() > k)
pq.poll(); // Remove smallest element
}
return pq.peek(); // Kth largest
}
}
/*
Example:
nums = {3,2,1,5,6,4}, k = 2
Output: 5
*/
15. Implement Observer Pattern
Definition: Implements Observer design pattern where observers are notified when subject changes.
import java.util.*;
interface Observer {
void update(String message);
}
class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer o) {
observers.add(o);
}
public void notifyObservers(String msg) {
for (Observer o : observers)
o.update(msg);
}
}
/*
Used when:
- Event notification systems
- Publish/Subscribe models
*/
16. Find Second Highest Salary
Definition: Finds second highest distinct salary using Java Stream API.
import java.util.*;
class Employee {
String name;
int salary;
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
public class SecondHighest {
public static void main(String[] args) {
List<Employee> list = List.of(
new Employee("A", 5000),
new Employee("B", 7000),
new Employee("C", 6000)
);
int salary = list.stream()
.map(e -> e.salary)
.distinct() // remove duplicates
.sorted(Comparator.reverseOrder())
.skip(1) // skip highest
.findFirst()
.orElse(0);
System.out.println(salary);
// Output: 6000
}
}
17. Design Parking Lot (Basic LLD)
Definition: Demonstrates basic object-oriented design for parking system.
class Car {}
class ParkingSpot {
private boolean occupied;
public boolean park() {
if (!occupied) {
occupied = true;
return true; // Car parked successfully
}
return false; // Spot already occupied
}
}
18. Implement Custom Comparator Sorting
Definition: Sorts objects by multiple fields using Comparator.
list.sort(Comparator
.comparing(Employee::getName)
.thenComparing(Employee::getSalary));
/*
First sorts by name,
If names equal → sorts by salary.
*/
19. Implement Read-Write Lock Example
Definition: Uses ReadWriteLock to allow multiple readers but only one writer.
import java.util.concurrent.locks.*;
class SharedResource {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public void read() {
lock.readLock().lock(); // acquire read lock
try {
System.out.println("Reading...");
} finally {
lock.readLock().unlock(); // release read lock
}
}
}
/*
Multiple threads can read simultaneously,
but write lock is exclusive.
*/
20. Word Frequency Counter from File
Definition: Reads a file and counts how many times each word appears.
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
public class WordFrequency {
public static void main(String[] args) throws Exception {
Map<String, Long> frequency =
Files.lines(Path.of("file.txt"))
.flatMap(line -> Arrays.stream(line.split("\\W+")))
.map(String::toLowerCase)
.filter(word -> !word.isBlank())
.collect(Collectors.groupingBy(
w -> w,
Collectors.counting()
));
System.out.println(frequency);
/*
Example Output:
{java=3, interview=2, code=1}
*/
}
}21. Implement Retry Mechanism
Definition: Retries an operation multiple times if it fails.
public class RetryExample {
public static void main(String[] args) {
int maxRetries = 3;
int attempt = 0;
while (attempt < maxRetries) {
try {
attempt++;
performOperation(); // Try operation
break; // Exit loop if successful
} catch (Exception e) {
System.out.println("Retry attempt: " + attempt);
if (attempt == maxRetries) {
System.out.println("Operation failed.");
}
}
}
}
static void performOperation() {
if (Math.random() < 0.7)
throw new RuntimeException("Failure");
System.out.println("Success");
}
}
/*
Output (random):
Retry attempt: 1
Retry attempt: 2
Success
*/
22. Parallel API Calls Using CompletableFuture
Definition: Executes multiple tasks in parallel and waits for all to complete.
import java.util.concurrent.*;
public class ParallelAPICalls {
public static void main(String[] args) {
CompletableFuture<String> api1 =
CompletableFuture.supplyAsync(() -> {
sleep(2); // Simulate delay
return "API1 Response";
});
CompletableFuture<String> api2 =
CompletableFuture.supplyAsync(() -> {
sleep(1);
return "API2 Response";
});
CompletableFuture<Void> combined =
CompletableFuture.allOf(api1, api2);
combined.join(); // Wait for both
System.out.println(api1.join());
System.out.println(api2.join());
/*
Output:
API1 Response
API2 Response
*/
}
private static void sleep(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (Exception ignored) {}
}
}
23. Check if String is Palindrome
Definition: Checks whether a string reads the same forward and backward.
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
System.out.println(isPalindrome(str));
// Output: true
}
static boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right))
return false;
left++;
right--;
}
return true;
}
}
24. Remove Duplicates from Array
Definition: Removes duplicate elements and keeps unique values.
import java.util.*;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4};
Set<Integer> set = new LinkedHashSet<>();
// LinkedHashSet maintains insertion order
for (int n : arr)
set.add(n);
System.out.println(set);
// Output: [1, 2, 3, 4]
}
}
25. Reverse Words in a Sentence
Definition: Reverses the order of words in a sentence.
public class ReverseWords {
public static void main(String[] args) {
String str = "Java is powerful";
String[] words = str.split(" ");
for (int i = words.length - 1; i >= 0; i--)
System.out.print(words[i] + " ");
// Output: powerful is Java
}
}
26. Find Missing Number in Array
Definition: Finds missing number from 1 to n using sum formula.
public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5};
int n = 5;
int expected = n * (n + 1) / 2; // Formula for sum of first n numbers
int actual = 0;
for (int num : arr)
actual += num;
System.out.println(expected - actual);
// Output: 3
}
}
27. Swap Two Numbers Without Third Variable
Definition: Swaps two numbers using XOR bitwise operation.
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println(a + " " + b);
// Output: 10 5
}
}
28. Count Occurrence of Each Character
Definition: Counts how many times each character appears in a string.
import java.util.*;
public class CharacterFrequency {
public static void main(String[] args) {
String str = "java";
Map<Character, Integer> map = new HashMap<>();
for (char c : str.toCharArray())
map.put(c, map.getOrDefault(c, 0) + 1);
System.out.println(map);
// Output: {j=1, a=2, v=1}
}
}
29. Sort Map by Value
Definition: Sorts a HashMap based on its values.
import java.util.*;
public class SortMapByValue {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 3);
map.put("B", 1);
map.put("C", 2);
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEach(System.out::println);
/*
Output:
B=1
C=2
A=3
*/
}
}
30. Custom Exception Example
Definition: Demonstrates creating and throwing a custom exception.
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}
public class CustomExceptionDemo {
public static void main(String[] args) throws Exception {
int age = 16;
if (age < 18)
throw new InvalidAgeException("Not eligible");
/*
Output:
Exception in thread "main" InvalidAgeException: Not eligible
*/
}
}
31. Check Balanced Parentheses
Definition: Checks whether brackets are properly balanced using Stack.
import java.util.*;
public class BalancedParentheses {
public static void main(String[] args) {
String str = "{[()]}";
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray()) {
if (c == '(' || c == '{' || c == '[')
stack.push(c);
else {
if (stack.isEmpty()) {
System.out.println(false);
return;
}
stack.pop();
}
}
System.out.println(stack.isEmpty());
// Output: true
}
}
32. Implement Comparable Example
Definition: Sorts objects using Comparable interface.
import java.util.*;
class Student implements Comparable<Student> {
int id;
Student(int id) {
this.id = id;
}
public int compareTo(Student s) {
return this.id - s.id; // ascending order
}
}
public class ComparableDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(3));
list.add(new Student(1));
Collections.sort(list);
for (Student s : list)
System.out.println(s.id);
// Output:
// 1
// 3
}
}
33. Lazy Initialization Using Holder Pattern
Definition: Thread-safe singleton without synchronization overhead.
class HolderSingleton {
private HolderSingleton() {}
private static class Holder {
static final HolderSingleton INSTANCE =
new HolderSingleton();
}
public static HolderSingleton getInstance() {
return Holder.INSTANCE;
}
}
34. Find Intersection of Two Arrays
Definition: Finds common elements between two arrays.
import java.util.*;
public class ArrayIntersection {
public static void main(String[] args) {
int[] a = {1,2,3,4};
int[] b = {3,4,5,6};
Set<Integer> set = new HashSet<>();
for (int n : a)
set.add(n);
for (int n : b)
if (set.contains(n))
System.out.print(n + " ");
// Output: 3 4
}
}
35. Check Power of Two
Definition: Checks whether a number is a power of 2 using bit manipulation.
public class PowerOfTwo {
public static void main(String[] args) {
int n = 16;
System.out.println((n > 0) && ((n & (n - 1)) == 0));
// Output: true
}
}
36. Deadlock Example
Definition: Demonstrates deadlock when two threads hold locks in opposite order.
public class DeadlockExample {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) {
new Thread(() -> {
synchronized (lock1) {
synchronized (lock2) {}
}
}).start();
new Thread(() -> {
synchronized (lock2) {
synchronized (lock1) {}
}
}).start();
}
/*
Both threads wait for each other's lock → Deadlock occurs
*/
}
37. Convert List to Map
Definition: Converts list of objects into a Map using Stream API.
import java.util.*;
import java.util.stream.*;
class User {
int id;
String name;
User(int id, String name) {
this.id = id;
this.name = name;
}
}
public class ListToMap {
public static void main(String[] args) {
List<User> list = List.of(
new User(1, "A"),
new User(2, "B")
);
Map<Integer, String> map =
list.stream()
.collect(Collectors.toMap(
u -> u.id,
u -> u.name
));
System.out.println(map);
// Output: {1=A, 2=B}
}
}
38. Implement Callable and Future
Definition: Demonstrates asynchronous task execution using Callable and Future.
import java.util.concurrent.*;
public class CallableExample {
public static void main(String[] args) throws Exception {
ExecutorService service = Executors.newSingleThreadExecutor();
Callable<String> task = () -> "Task Done";
Future<String> future = service.submit(task);
System.out.println(future.get());
// Output: Task Done
service.shutdown();
}
}39. Reverse Integer
Definition: Reverses digits of an integer number.
public class ReverseInteger {
public static void main(String[] args) {
int num = 1234;
int reversed = 0;
while (num != 0) {
int digit = num % 10; // Extract last digit
reversed = reversed * 10 + digit;
num = num / 10; // Remove last digit
}
System.out.println(reversed);
// Output: 4321
}
}
40. Check Armstrong Number
Definition: Checks if a number equals the sum of cubes of its digits.
Example:
153 → 1³ + 5³ + 3³ = 153public class Armstrong {
public static void main(String[] args) {
int n = 153;
int temp = n;
int sum = 0;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp = temp / 10;
}
System.out.println(sum == n);
// Output: true
}
}
41. Factorial Using Recursion
Definition: Computes factorial of a number (n! = n × (n-1) × ... × 1).
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120public class Factorial {
static int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(5));
// Output: 120
}
}
42. Fibonacci Series (Iterative)
Definition: Prints Fibonacci sequence where each number is sum of previous two numbers.
Sequence:
0, 1, 1, 2, 3, 5, 8...public class Fibonacci {
public static void main(String[] args) {
int n = 7;
int first = 0;
int second = 1;
System.out.print(first + " " + second + " ");
for (int i = 2; i < n; i++) {
int next = first + second;
System.out.print(next + " ");
first = second;
second = next;
}
// Output: 0 1 1 2 3 5 8
}
}
43. Check Prime Number
Definition: Checks whether a number is prime (divisible only by 1 and itself).
public class PrimeCheck {
public static void main(String[] args) {
int n = 17;
boolean isPrime = true;
if (n <= 1)
isPrime = false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
System.out.println(isPrime);
// Output: true
}
}
44. Find Largest Element in Array
Definition: Finds maximum element in an array.
public class LargestElement {
public static void main(String[] args) {
int[] arr = {10, 5, 20, 8};
int max = arr[0];
for (int n : arr)
if (n > max)
max = n;
System.out.println(max);
// Output: 20
}
}
45. Count Vowels in String
Definition: Counts number of vowels in a string.
public class CountVowels {
public static void main(String[] args) {
String str = "Java Programming";
int count = 0;
for (char c : str.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) != -1)
count++;
}
System.out.println(count);
// Output: 5
}
}
46. Remove Whitespaces from String
Definition: Removes all whitespace characters from string.
public class RemoveSpaces {
public static void main(String[] args) {
String str = "Java Interview Guide";
String result = str.replaceAll("\\s+", "");
System.out.println(result);
// Output: JavaInterviewGuide
}
}
47. Find GCD (Greatest Common Divisor)
Definition: Finds greatest common divisor of two numbers using Euclidean algorithm.
public class GCD {
public static void main(String[] args) {
int a = 54;
int b = 24;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
System.out.println(a);
// Output: 6
}
}
48. Convert String to Integer (Manual Parsing)
Definition: Converts numeric string to integer without using Integer.parseInt().
public class StringToInt {
public static void main(String[] args) {
String str = "1234";
int result = 0;
for (char c : str.toCharArray()) {
result = result * 10 + (c - '0');
}
System.out.println(result);
// Output: 1234
}
}
49. Check if Array is Sorted
Definition: Checks whether array elements are sorted in ascending order.
public class CheckSorted {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
boolean sorted = true;
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
sorted = false;
break;
}
}
System.out.println(sorted);
// Output: true
}
}
50. Implement Stack Using Array
Definition: Custom implementation of Stack using array.
class Stack {
private int[] arr = new int[5];
private int top = -1;
public void push(int value) {
if (top == arr.length - 1) {
System.out.println("Stack Overflow");
return;
}
arr[++top] = value;
}
public int pop() {
if (top == -1) {
System.out.println("Stack Underflow");
return -1;
}
return arr[top--];
}
}
public class StackDemo {
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(10);
stack.push(20);
System.out.println(stack.pop());
// Output: 20
}
}
Stream API Coding Problems1. Filter Even Numbers
Definition: Filters even numbers from a list.
import java.util.*;
public class EvenNumbers {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
List<Integer> result = list.stream()
.filter(n -> n % 2 == 0)
.toList();
System.out.println(result);
// Output: [2, 4, 6]
}
}
2. Convert List of Strings to Uppercase
Definition: Converts all strings to uppercase.
List<String> list = Arrays.asList("java","stream");
List<String> result = list.stream()
.map(String::toUpperCase)
.toList();
System.out.println(result);
// Output: [JAVA, STREAM]
3. Find Sum of All Numbers
Definition: Calculates sum using Stream.
List<Integer> list = Arrays.asList(1,2,3,4);
int sum = list.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum);
// Output: 10
4. Find Maximum Element
Definition: Finds maximum value from list.
List<Integer> list = Arrays.asList(10,5,30,20);
int max = list.stream()
.max(Integer::compare)
.orElse(0);
System.out.println(max);
// Output: 30
5. Count Occurrences of Each Element
Definition: Counts frequency of elements using groupingBy.
List<String> list = Arrays.asList("a","b","a","c","b");
Map<String, Long> freq =
list.stream()
.collect(Collectors.groupingBy(
s -> s,
Collectors.counting()
));
System.out.println(freq);
// Output: {a=2, b=2, c=1}
6. Remove Duplicate Elements
Definition: Removes duplicates using distinct().
List<Integer> list = Arrays.asList(1,2,2,3,3,4);
List<Integer> result = list.stream()
.distinct()
.toList();
System.out.println(result);
// Output: [1, 2, 3, 4]
7. Sort List in Descending Order
Definition: Sorts elements in reverse order.
List<Integer> list = Arrays.asList(3,1,4,2);
List<Integer> sorted = list.stream()
.sorted(Comparator.reverseOrder())
.toList();
System.out.println(sorted);
// Output: [4, 3, 2, 1]
8. Find Second Highest Number
Definition: Finds second highest distinct number.
List<Integer> list = Arrays.asList(10,20,30,40);
int second = list.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.orElse(0);
System.out.println(second);
// Output: 30
9. Check if All Elements Match Condition
Definition: Checks if all elements are even.
List<Integer> list = Arrays.asList(2,4,6);
boolean allEven = list.stream()
.allMatch(n -> n % 2 == 0);
System.out.println(allEven);
// Output: true
10. Join Strings with Comma
Definition: Joins strings into single comma-separated string.
List<String> list = Arrays.asList("Java","Stream","API");
String result = list.stream()
.collect(Collectors.joining(", "));
System.out.println(result);
// Output: Java, Stream, API
11. Convert List to Map
Definition: Converts list to map using key and value mapping.
List<String> list = Arrays.asList("A","B","C");
Map<String, Integer> map =
list.stream()
.collect(Collectors.toMap(
s -> s,
String::length
));
System.out.println(map);
// Output: {A=1, B=1, C=1}
12. Partition Even and Odd Numbers
Definition: Separates numbers into even and odd groups.
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
Map<Boolean, List<Integer>> result =
list.stream()
.collect(Collectors.partitioningBy(
n -> n % 2 == 0
));
System.out.println(result);
// Output: {false=[1, 3, 5], true=[2, 4, 6]}
13. Flatten List of Lists
Definition: Converts nested list into single list.
List<List<Integer>> list = Arrays.asList(
Arrays.asList(1,2),
Arrays.asList(3,4)
);
List<Integer> result = list.stream()
.flatMap(Collection::stream)
.toList();
System.out.println(result);
// Output: [1, 2, 3, 4]
14. Find Average of Numbers
Definition: Calculates average using stream.
List<Integer> list = Arrays.asList(10,20,30);
double avg = list.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0);
System.out.println(avg);
// Output: 20.0
15. Find First Element
Definition: Retrieves first element from stream.
List<String> list = Arrays.asList("Java","Python");
String first = list.stream()
.findFirst()
.orElse("None");
System.out.println(first);
// Output: Java
16. Count Elements
Definition: Counts number of elements in list.
List<Integer> list = Arrays.asList(1,2,3,4);
long count = list.stream()
.count();
System.out.println(count);
// Output: 4
17. Filter Strings Starting with Letter
Definition: Filters strings starting with 'J'.
List<String> list = Arrays.asList("Java","Spring","JPA");
List<String> result = list.stream()
.filter(s -> s.startsWith("J"))
.toList();
System.out.println(result);
// Output: [Java, JPA]
18. Convert Array to Stream
Definition: Converts array into stream and prints elements.
int[] arr = {1,2,3};
Arrays.stream(arr)
.forEach(System.out::println);
/*
Output:
1
2
3
*/
19. Check if Any Element Matches
Definition: Checks if any number is greater than 10.
List<Integer> list = Arrays.asList(5,15,3);
boolean exists = list.stream()
.anyMatch(n -> n > 10);
System.out.println(exists);
// Output: true
20. Find Longest String
Definition: Finds string with maximum length.
List<String> list = Arrays.asList("Java","Programming","API");
String longest = list.stream()
.max(Comparator.comparingInt(String::length))
.orElse("");
System.out.println(longest);
// Output: Programming
21. Skip First N Elements
List<Integer> list = Arrays.asList(1,2,3,4,5);
List<Integer> result = list.stream()
.skip(2)
.toList();
System.out.println(result);
// Output: [3, 4, 5]
22. Limit Stream
List<Integer> list = Arrays.asList(1,2,3,4,5);
List<Integer> result = list.stream()
.limit(3)
.toList();
System.out.println(result);
// Output: [1, 2, 3]
23. Group Strings by Length
List<String> list = Arrays.asList("Java","API","Spring");
Map<Integer, List<String>> grouped =
list.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(grouped);
// Output: {3=[API], 4=[Java], 6=[Spring]}
24. Convert Stream to Set
List<Integer> list = Arrays.asList(1,2,2,3);
Set<Integer> set = list.stream()
.collect(Collectors.toSet());
System.out.println(set);
// Output: [1, 2, 3]
25. Parallel Stream Example
Definition: Processes stream in parallel.
List<Integer> list = Arrays.asList(1,2,3,4,5);
list.parallelStream()
.forEach(System.out::println);
/*
Output order may vary (parallel execution)
*/26. Find Top 3 Highest Numbers
Definition: Returns top 3 highest distinct numbers from list.
List<Integer> list = Arrays.asList(10, 20, 50, 40, 50, 30);
List<Integer> top3 = list.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.limit(3)
.toList();
System.out.println(top3);
// Output: [50, 40, 30]
27. Find Duplicate Elements
Definition: Finds duplicate elements using groupingBy.
List<Integer> list = Arrays.asList(1,2,3,2,4,1);
List<Integer> duplicates = list.stream()
.collect(Collectors.groupingBy(n -> n, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.toList();
System.out.println(duplicates);
// Output: [1, 2]
28. Group Employees by Department
Definition: Groups employees based on department.
class Employee {
String name;
String dept;
Employee(String name, String dept) {
this.name = name;
this.dept = dept;
}
}
List<Employee> list = Arrays.asList(
new Employee("A", "IT"),
new Employee("B", "HR"),
new Employee("C", "IT")
);
Map<String, List<Employee>> grouped =
list.stream()
.collect(Collectors.groupingBy(e -> e.dept));
System.out.println(grouped.keySet());
// Output: [IT, HR]
29. Find Employee with Highest Salary
Definition: Finds employee having maximum salary.
class Emp {
String name;
int salary;
Emp(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
List<Emp> list = Arrays.asList(
new Emp("A", 5000),
new Emp("B", 7000),
new Emp("C", 6000)
);
Emp highest = list.stream()
.max(Comparator.comparingInt(e -> e.salary))
.orElse(null);
System.out.println(highest.name);
// Output: B
30. Group by Department and Count
Definition: Counts employees in each department.
Map<String, Long> count =
list.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.counting()
));
System.out.println(count);
// Output: {IT=2, HR=1}
31. Find Second Highest Salary per Department
Definition: Finds second highest salary employee within each department.
Map<String, Optional<Emp>> result =
list.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.collectingAndThen(
Collectors.toList(),
l -> l.stream()
.sorted(Comparator.comparingInt(e -> -e.salary))
.skip(1)
.findFirst()
)
));
32. Convert List to Concurrent Map
Definition: Converts list to thread-safe concurrent map.
ConcurrentMap<String, Integer> map =
list.stream()
.collect(Collectors.toConcurrentMap(
e -> e.name,
e -> e.salary
));
33. Find Most Frequent Element
Definition: Finds element that appears most times.
List<String> list = Arrays.asList("A","B","A","C","A","B");
String mostFrequent =
list.stream()
.collect(Collectors.groupingBy(s -> s, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null);
System.out.println(mostFrequent);
// Output: A
34. Flatten Nested Object Fields
Definition: Flattens nested lists into single list.
class Order {
List<String> items;
Order(List<String> items) {
this.items = items;
}
}
List<Order> orders = Arrays.asList(
new Order(Arrays.asList("A","B")),
new Order(Arrays.asList("C"))
);
List<String> allItems =
orders.stream()
.flatMap(o -> o.items.stream())
.toList();
System.out.println(allItems);
// Output: [A, B, C]
35. Calculate Total Salary by Department
Definition: Calculates total salary per department.
Map<String, Integer> totalSalary =
list.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.summingInt(e -> e.salary)
));
System.out.println(totalSalary);
// Output: {IT=11000, HR=...}
36. Partition Employees by Salary Threshold
Definition: Splits employees into two groups based on salary condition.
Map<Boolean, List<Emp>> result =
list.stream()
.collect(Collectors.partitioningBy(
e -> e.salary > 6000
));
37. Find Longest Word in Sentence
Definition: Finds longest word in a sentence.
String sentence = "Java Stream API Interview";
String longest =
Arrays.stream(sentence.split(" "))
.max(Comparator.comparingInt(String::length))
.orElse("");
System.out.println(longest);
// Output: Interview
38. Remove Null Values
Definition: Filters out null values from list.
List<String> list = Arrays.asList("A", null, "B");
List<String> cleaned =
list.stream()
.filter(Objects::nonNull)
.toList();
System.out.println(cleaned);
// Output: [A, B]
39. Generate Infinite Stream
Definition: Generates infinite stream and limits results.
Stream.iterate(1, n -> n + 1)
.limit(5)
.forEach(System.out::println);
/*
Output:
1
2
3
4
5
*/
40. Find Duplicate Characters in String
Definition: Finds duplicate characters using Stream API.
String str = "programming";
List<Character> duplicates =
str.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.toList();
System.out.println(duplicates);
// Output: [r, g, m]
41. Convert Stream to Array
Definition: Converts Stream into array.
String[] arr =
list.stream()
.toArray(String[]::new);
42. Merge Two Lists
Definition: Merges two lists into one stream.
List<Integer> merged =
Stream.concat(list1.stream(), list2.stream())
.toList();
43. Custom Collector Example
Definition: Demonstrates creating custom collector.
String result =
list.stream()
.collect(Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString
));
44. Find First Repeated Element
Definition: Finds first duplicate element in list.
Set<Integer> seen = new HashSet<>();
Integer firstRepeat =
list.stream()
.filter(n -> !seen.add(n))
.findFirst()
.orElse(null);
System.out.println(firstRepeat);
45. Calculate Median Using Streams
Definition: Calculates median of sorted list.
List<Integer> sorted = list.stream().sorted().toList();
int median = sorted.get(sorted.size()/2);
System.out.println(median);
46. Find All Palindromes in List
Definition: Filters all palindrome strings.
List<String> palindromes =
list.stream()
.filter(s -> new StringBuilder(s).reverse().toString().equals(s))
.toList();
47. Check if List Contains Duplicate
Definition: Checks whether list contains duplicates.
boolean hasDuplicate =
list.stream().distinct().count() != list.size();
48. Map to Custom Object
Definition: Maps list elements to custom objects.
List<Emp> empList =
names.stream()
.map(name -> new Emp(name, 5000))
.toList();
49. Parallel Stream with Reduce
Definition: Uses parallel stream to compute sum.
int sum =
list.parallelStream()
.reduce(0, Integer::sum);
System.out.println(sum);
50. Custom Sorting Based on Multiple Fields
Definition: Sorts objects using multiple comparators.
List<Emp> sorted =
list.stream()
.sorted(Comparator
.comparing((Emp e) -> e.dept)
.thenComparing(e -> e.salary))
.toList();51. Group by Department and Average Salary
Definition: Calculates average salary per department.
Map<String, Double> avgSalary =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.averagingInt(e -> e.salary)
));
System.out.println(avgSalary);
// Output: {IT=5500.0, HR=4000.0}
52. Group by Department and Find Highest Salary
Definition: Finds highest paid employee per department.
Map<String, Optional<Employee>> highest =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.maxBy(Comparator.comparingInt(e -> e.salary))
));
53. Nested Grouping (Department → Age Group)
Definition: Groups employees by department and then by age.
Map<String, Map<Integer, List<Employee>>> nested =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.groupingBy(e -> e.age)
));
54. Convert Grouping Result to Custom Summary Object
Definition: Uses collectingAndThen to post-process grouped data.
Map<String, Long> count =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.collectingAndThen(
Collectors.counting(),
c -> c
)
));
55. Count Total Characters in All Strings
Definition: Sums total length of all strings.
int totalLength =
list.stream()
.collect(Collectors.summingInt(String::length));
System.out.println(totalLength);
56. Concatenate Strings with Prefix and Suffix
Definition: Uses joining with prefix and suffix.
String result =
list.stream()
.collect(Collectors.joining(", ", "[", "]"));
System.out.println(result);
// Output: [A, B, C]
57. Group and Map to Specific Field
Definition: Groups employees by department but stores only names.
Map<String, List<String>> result =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.mapping(e -> e.name, Collectors.toList())
));
58. Count Unique Elements
Definition: Counts unique elements using toSet collector.
long uniqueCount =
list.stream()
.collect(Collectors.toSet())
.size();
System.out.println(uniqueCount);
59. Create Unmodifiable List
Definition: Collects elements into unmodifiable list.
List<String> unmodifiable =
list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
));
60. Group and Sum Multiple Fields
Definition: Groups by department and sums salary.
Map<String, Integer> sumSalary =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.summingInt(e -> e.salary)
));
61. Create Map with Duplicate Keys Handling
Definition: Resolves duplicate keys in toMap.
Map<String, Integer> map =
employees.stream()
.collect(Collectors.toMap(
e -> e.name,
e -> e.salary,
(oldVal, newVal) -> oldVal
));
62. Partition and Count
Definition: Partitions employees by salary threshold and counts each group.
Map<Boolean, Long> result =
employees.stream()
.collect(Collectors.partitioningBy(
e -> e.salary > 5000,
Collectors.counting()
));
63. Group by Length and Join Strings
Definition: Groups strings by length and joins them.
Map<Integer, String> grouped =
list.stream()
.collect(Collectors.groupingBy(
String::length,
Collectors.joining(", ")
));
64. Find Minimum Salary per Department
Definition: Finds minimum salary employee per department.
Map<String, Optional<Employee>> minSalary =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.minBy(Comparator.comparingInt(e -> e.salary))
));
65. Multi-Level Mapping
Definition: Groups by department and converts employees to names list.
Map<String, List<String>> result =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.mapping(e -> e.name, Collectors.toList())
));
66. Calculate Summary Statistics
Definition: Generates statistical summary (min, max, avg, sum).
IntSummaryStatistics stats =
employees.stream()
.collect(Collectors.summarizingInt(e -> e.salary));
System.out.println(stats);
// Output: IntSummaryStatistics{count=..., sum=..., min=..., average=..., max=...}
67. Group and Collect into TreeSet
Definition: Groups and collects into sorted set.
Map<String, Set<String>> result =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.mapping(
e -> e.name,
Collectors.toCollection(TreeSet::new)
)
));
68. Group and Find Top Salary per Department
Definition: Finds max salary per department.
Map<String, Integer> result =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.collectingAndThen(
Collectors.maxBy(
Comparator.comparingInt(e -> e.salary)
),
opt -> opt.map(e -> e.salary).orElse(0)
)
));
69. Flatten and Collect to Set
Definition: Flattens nested lists and collects unique values.
Set<String> result =
orders.stream()
.flatMap(o -> o.items.stream())
.collect(Collectors.toSet());
70. Group by First Character
Definition: Groups strings by first character.
Map<Character, List<String>> result =
list.stream()
.collect(Collectors.groupingBy(
s -> s.charAt(0)
));
71. Count Character Frequency in String
Definition: Counts frequency of each character.
Map<Character, Long> freq =
str.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(
c -> c,
Collectors.counting()
));
72. Custom Downstream Collector
Definition: Uses reducing collector.
int total =
employees.stream()
.collect(Collectors.reducing(
0,
e -> e.salary,
Integer::sum
));
73. Create LinkedHashMap from Stream
Definition: Maintains insertion order.
Map<String, Integer> map =
list.stream()
.collect(Collectors.toMap(
s -> s,
String::length,
(a,b) -> a,
LinkedHashMap::new
));
74. Group and Count Distinct Values
Definition: Counts distinct salaries per department.
Map<String, Long> result =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.mapping(
e -> e.salary,
Collectors.collectingAndThen(
Collectors.toSet(),
Set::size
)
)
));
75. Create Map of Department → Average + Count
Definition: Collects multiple aggregations using collectingAndThen.
Map<String, Double> result =
employees.stream()
.collect(Collectors.groupingBy(
e -> e.dept,
Collectors.averagingInt(e -> e.salary)
));