Java Stream Coding Interview Questions and Solutions


Java Stream API introduced in Java 8 and use functional way (lambda function f(x) -> y) to process a collection. It operates over a source data and returns a transformed immutable object. It is one of the most frequently asked interview topic. If you're preparing for Java developer roles, make sure to go through the below consolidated and compiled coding question and answers to bookmark and practice.

 Q. Convert a collection of string to upper case:

List<String> list = Arrays
.asList("Bob", "Piter", "Andi", "Joy");
List<String> listUpper = list
.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());

System.out.println("listUpper - "+listUpper);

Output:

listUpper - [BOB, PITER, ANDI, JOY]

Q. Find Max value from a collection of integer:

List<Integer> listInt = Arrays
.asList(4,5,7,3,23,89);
Optional<Integer> value = listInt
.stream()
.max(Integer::compare);

System.out.println("Max Value - "+value.orElse(0));

Output:

Max Value - 89

Q. Compare and return a collection of entries found in another collection:

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

List<Integer> result = list1
.stream()
.filter(l1 ->
list2.stream()
.anyMatch(l2 -> l1 == l2))
.collect(Collectors.toList());

System.out.println("result - "+result);

Output: 

result - [3, 2, 7]

Q. Compare and return a collection of entries not-found in another collection:

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

List<Integer> result = list1
.stream()
.filter(l1 ->
list2.stream()
.noneMatch(l2 -> l1 == l2))
.collect(Collectors.toList());

System.out.println("result - "+result);

Output:

Max Value - 89

Q. Compare and return a collection of all entries found in another collection:

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

List<Integer> result = list1
.stream()
.filter(l1 ->
list2.stream()
.allMatch(l2 -> l1 == l2))
.collect(Collectors.toList());

System.out.println("result - "+result);

Output:

result111132 - []

Q. Pair entries of two integer collections:

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

Map<Integer, Integer> result = IntStream.range(0, list1.size())
.boxed()
.collect(Collectors.toMap(i -> list1.get(i), i -> list2.get(i)));

System.out.println("result - "+result);

Output:

result - {2=2, 3=3, 5=4, 6=7, 7=8}

Q. Given a list find the index pair whose add value is equal to the given number:

Integer target = 10;
List<Integer> list = Arrays.asList(3,4,2,8,7);

List<Map<Integer, Integer>> result =
IntStream.range(0, list.size())
.boxed()
.flatMap(index ->
IntStream.range(index + 1, list.size())
.filter(j -> list.get(index) + list.get(j) == target)
.mapToObj(j -> Map.of(index, j))
).collect(Collectors.toList());

System.out.println("result - "+result);

Output:

result - [{0=4}, {2=3}]

Q. Find the employee earning highest salary:

Employee emp1 = new Employee(1, "Bob", 100, 10);
Employee emp2 = new Employee(2, "Alex", 101, 11);
Employee emp3 = new Employee(3, "Nick", 102, 10);
Employee emp4 = new Employee(4, "Jones", 105, 10);
Employee emp5 = new Employee(5, "Berry", 110, 10);
Employee emp6 = new Employee(6, "Jack", 107, 12);

List<Employee> employees = List.of(emp3, emp1, emp3, emp4, emp5, emp6);
Employee employee = employees
.stream()
.max(Comparator.comparing(Employee::getSalary))
.orElse(null);

System.out.println("Employee Earning Highest Salary - "+employee.getSalary());

Output:

Employee Highest salary - 110.0

Q. Sorting a collection employees based on salary in descending order:

List<Employee> sortedEmployees = employees.stream()
.sorted(Comparator.comparing(Employee::getSalary)
.reversed())
.collect(Collectors.toList());

sortedEmployees.stream()
.forEach(employee ->
System.out.println("Employee Id - "+employee.getId()+", Name - "+employee.getName()+", Salary - "+employee.getSalary())
);

Output:

Employee Id - 5, Name - Berry, Salary - 110.0
Employee Id - 6, Name - Jack, Salary - 107.0
Employee Id - 4, Name - Jones, Salary - 105.0
Employee Id - 3, Name - Nick, Salary - 102.0
Employee Id - 3, Name - Nick, Salary - 102.0
Employee Id - 1, Name - Bob, Salary - 100.0

Q. Find 2 employees earning highest salary from each department:

Map<Double, List<Employee>> deptMaxSalEmps = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDeptId,
Collectors.collectingAndThen(
Collectors.toList(),
emps -> emps.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary)
.reversed())
.limit(3).collect(Collectors.toList()))
)
);

deptMaxSalEmps.entrySet()
.stream()
.forEach(entry -> {
Double dept = entry.getKey();
System.out.println("Department - "+dept);
List<Employee> employees = entry.getValue();
employees.stream()
.forEach(employee ->
System.out.println(
"Employee Name - "+employee.getName()+", " +
"Salary - "+employee.getSalary()));
});

Output:

Department - 10.0
Employee Name - Berry, Salary - 110.0
Employee Name - Jones, Salary - 105.0
Employee Name - Nick, Salary - 102.0
Department - 12.0
Employee Name - Jack, Salary - 107.0
Department Id: 10.0 and Average Salary: 103.8
Department Id: 12.0 and Average Salary: 107.0
Q. List employee names in each department:
Employee emp1 = new Employee(1, "Bob", 100, 10);
Employee emp2 = new Employee(2, "Alex", 101, 14);
Employee emp3 = new Employee(3, "Nick", 102, 10);
Employee emp4 = new Employee(4, "Jones", 105, 10);
Employee emp5 = new Employee(5, "Berry", 110, 10);
Employee emp6 = new Employee(6, "Jack", 107, 12);

List<Employee> employees = List.of(emp1, emp2, emp3, emp4, emp5, emp6);

Map<Double, List<String>> deptEmployees = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDeptId,
Collectors.mapping(Employee::getName, Collectors.toList())
)
);

deptEmployees.entrySet()
.stream()
.forEach(entry -> {
Double dept = entry.getKey();
System.out.println("Department - "+dept);
List<String> employeeNames = entry.getValue();
employeeNames.stream()
.forEach(employeeName ->
System.out.println("Employee Name - "+employeeName));
});

Output:

Department - 10.0
Employee Name - Bob
Employee Name - Nick
Employee Name - Jones
Employee Name - Berry
Department - 12.0
Employee Name - Jack
Department - 14.0
Employee Name - Alex
Map<Double, Double> depAvgSalEmp = employees.stream()
.collect(Collectors.groupingBy(Employee::getDeptId,
Collectors.averagingDouble(Employee::getSalary))
);
depAvgSalEmp.entrySet()
.stream()
.forEach(item ->{
System.out.println("Department Id: "+item.getKey()+" and Average Salary: "+item.getValue());
});

Output:

Department Id - 10.0 and Average Salary - 104.25
Department Id - 12.0 and Average Salary - 107.0
Department Id - 14.0 and Average Salary - 101.0
Map<Double, Double> deptSumSalEmp = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDeptId,
Collectors.summingDouble(Employee::getSalary)
)
);
deptSumSalEmp.entrySet().stream()
.forEach(entry -> {
System.out.println("Dept Id - "+entry.getKey()+", Total Salary -"+entry.getValue());
});

Output:

Dept Id - 10.0, Total Salary -417.0
Dept Id - 12.0, Total Salary -107.0
Dept Id - 14.0, Total Salary -101.0
List<Integer> iList = List.of(10,2,6,4,8);
List<Integer> sortedList = iList.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted List - "+sortedList);

Output:

Sorted List - [2, 4, 6, 8, 10]
List<Integer> iList = List.of(10,2,6,4,8);
int maxNumber = iList.stream()
.max(Integer::compare)
.orElse(0);

System.out.println("maxNumber - "+maxNumber);

Output:

maxNumber - 10
List<Integer> iList = List.of(10,2,6,4,8);
int sumOfAll = iList.stream()
.reduce(0, (n1, n2) -> n1 + n2);

System.out.println("Sum of all integer: "+sumOfAll);

Output:

Sum of all integer: 30
Q. Find the window average size:
int window = 3;
List<Double> wList = IntStream.range(0,(iList.size() - (window - 1)))
.mapToObj(i -> iList.subList(i, i+window))
.map(item -> item.stream()
.collect(Collectors.averagingInt(Integer::intValue)))
.collect(Collectors.toList());

System.out.println("Window List - "+wList);

Output:

Window List - [6.0, 4.0, 6.0]
Q. Find the count of each numbers reptation from a given collection of integer:
List<Integer> iList2 = List.of(10,2,6,4,8,2,10,2,4,2,10);
Map<Integer, Long> groupByCount = iList2.stream()
.collect(Collectors.groupingBy(Integer::intValue, Collectors.counting()));

System.out.println("groupByCount - "+groupByCount);

Output:

groupByCount - {2=4, 4=2, 6=1, 8=1, 10=3}
List<String> sList = List.of("a", "b", "a", "d", "c");
Map<String, Long> groupByCountString = sList.stream()
.collect(Collectors
.groupingBy(String::valueOf, Collectors.counting()));

System.out.println("Group By Count of Strings - "+groupByCountString);

Output:

Group By Count of Strings - {a=2, b=1, c=1, d=1}
Q. Reverse a given string using Java Stream API:
String inputStr = "Pramoda";
String revStr = IntStream.range(0, inputStr.length())
.mapToObj(index -> inputStr.charAt(inputStr.length() - 1 - index))
.map(String::valueOf)
.collect(Collectors.joining());

System.out.println("Reverse String - "+revStr);

Output:

revStr - adomarP
Q. Find the number of employee in each department:
Map<Integer, Long> deptEmpCount = employees.stream()
.collect(Collectors.groupingBy(
Employee::getId,
Collectors.counting()
)
);

System.out.println("Department and employee count - "+deptEmpCount);

Output:

Department and employee count - {10=4, 12=1, 14=1}

// rangeClosed() -> Includes the last element
// range() -> Do not includes the last element
int sum = IntStream.rangeClosed(1, 10)
.boxed()
.reduce(0, (v1, v2) -> v1 + v2);

System.out.println("sum - "+sum);

Output:

sum - 55
int sumN = 0;
Integer num = 123;
sumN = String
.valueOf(num)
.chars()
.map(c -> Character.getNumericValue(c))
.sum();

System.out.println("Sum of Digits - "+sumN);

Output:

Sum of Digits - 6
List<Integer> integerList = List.of(3,4,5,6,2,3,4,6,8);
Map<Integer, Long> intMapList = integerList
.stream()
.collect(Collectors.groupingBy(
Integer::intValue,
Collectors.counting())
);

intMapList.entrySet()
.stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.map(Map.Entry::getKey)
.ifPresent(entry -> System.out.println("Number with max repetition - "+entry));

Output:

Number with max repetition - 3
List<String> strList = List.of("madam", "kadak", "level", "room", "121");
Map<String, Boolean> mB = strList.stream()
.collect(
Collectors.toMap(
str -> str,
str -> str.equals(new StringBuffer(str).reverse().toString()) ? true : false
)
);

System.out.println("strList - "+strList);

Output:

strList - [madam, kadak, level, room, 121]
Q. Find the character with maximum occurance:
String iString = "hipramodahelloo";
Map<Character, Long> chCountList = iString.chars()
.mapToObj(ch -> (char)ch)
.collect(Collectors.groupingBy(
Character::charValue,
Collectors.counting()
)
);

List<Character> cList = chCountList.entrySet()
.stream()
.min(Comparator.comparingDouble(Map.Entry::getValue))
.map(Map.Entry::getKey)
.stream()
.collect(Collectors.toList());

System.out.println("Character with min occurrence - "+cList);

Output:

Character with min occurrence - {p=1, a=2, r=1, d=1, e=1, h=2, i=1, l=2, m=1, o=3}
List<Integer> intList = List.of(393,44,51,6,2,33453,231,2341,8);
List<Integer> aList = intList.stream()
.filter(n -> n%10 == 1)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());

System.out.println("Integer ends with 1 - "+aList);

Output:

Integer ends with 1 - [2341, 231, 51]
String string = "Hello Pramoda Kumar Sabat what are you doing";
String stringWithMaxLength = Arrays.stream(string.split(" "))
.max(Comparator.comparing(String::length))
.get();

System.out.println("Longest element in the string - "+stringWithMaxLength);

Output:

Longest element in the string - Pramoda

List<Integer> nList = List.of(-10, 2, 4,8,15,11);
int target = 5;
int closestNumIndex = IntStream.range(0, nList.size())
.boxed()
.min(Comparator
.comparing(index ->
Math.abs(nList.get(index) - target))
)
.get();

System.out.println("Closest Index of the input value 5 is - "+closestNumIndex);
Output:
Closest Index of  the input value - 2
List<Integer> nList = List.of(2,4,8,15,11,2,11);
boolean isListContainsPrime = nList
.stream()
.anyMatch(RunApplication::isPrime);
public static Boolean isPrime(Integer num){
if(num <= 1) return false;
if(num == 2) return false;
return !IntStream.range(2, num).anyMatch(a -> (num % a == 0));
}
Output:
Is contains prime - true
int pageNo = 4;
int perPage = 3;
List<Integer> records = List.of(6,4,3,6,1,8,2,5,7,10,56,34);
int pageSize = (int)Math.ceil((double)records.size()/perPage);

records.stream()
.skip((pageNo - 1) * (pageSize - 1))
.limit(perPage)
.forEach(page -> {
System.out.println("page - "+page);
});
Output:
page - 10
page - 56
page - 34
String name = "madam";
boolean isPalindrome = IntStream
.range(0, name.length()/2)
.allMatch(i ->
name.charAt(i) == name.charAt(name.length() - 1 -i));
System.out.println("Is palindrome - "+isPalindrome);
Output:
Is palindrome - true
List<Integer> inputList = List.of(9,4,6,-2,3,1);
Set inputSet = inputList.stream()
.filter(input -> input > 0)
.collect(Collectors.toSet());
int smallestMissingNumber = IntStream.iterate(1, i-> i+1)
.filter(n -> !inputSet.contains(n))
.findFirst().orElse(1);

System.out.println("Smallest Missing Number - "+smallestMissingNumber);
Output:
Smallest Missing Number - 2
String input = "swiss";
Character non_repeating_char = input.chars()
.mapToObj(ch -> (char)ch)
.collect(Collectors.groupingBy(
ch -> ch,
LinkedHashMap::new,
Collectors.counting()
)).entrySet()
.stream()
.filter(item -> item.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(' ');
System.out.println("First non repeating char - "+non_repeating_char);
Output:
First non repeating char - w
Q. Find if a string is valid or not. Every start brace must have and end brace otherwise invalid:
String inputString = "ac(ra{man})";
Deque<Character> queue = new ArrayDeque();
boolean isValid = false;
for(char ch : inputString.toCharArray()){
if(ch == '(' || ch == '{'){
queue.push(ch);
} else if(ch == ')' || ch == '}'){
isValid = !queue.isEmpty();
char open = queue.pop();
if(ch == '(' && open != ')' || ch == '{' && open != '}'){
valid = false;
}
}
isValid = queue.isEmpty();
}

System.out.println("Is valid - "+isValid);
Output:
Is valid - true
Q. Print a given string without repeating chars (Elements repeating char from a given string) :
String inString = "aeeksforaeeks";
StringBuffer outString = new StringBuffer();
outString.append(inputString.charAt(0));

for(int i = 1; i < inString.length(); i++){
if(inString.charAt(i) != inString.charAt(i - 1)){
outString.append(inString.charAt(i));
}
}
System.out.println("String without repeating chars - "+outString.toString());
Output:
String without repeating chars - aeksforaeks
Q. Find if two strings are anagrams (When chars are equal even if not in order):
Using Stream API:
String iStr = "Pramoda";
String iStr1 = "ramodaP";

String r11 = iStr.chars()
.sorted()
.mapToObj(a -> (char) a)
.collect(Collectors.toList())
.stream().map(String::valueOf)
.collect(Collectors.joining());

String r21 = iStr1.chars()
.sorted()
.mapToObj(c -> (char) c)
.collect(Collectors.toList())
.stream().map(String::valueOf)
.collect(Collectors.joining());

System.out.println("Equal - "+r11.equals(r21));
Output: 
Equal - true
Using Arrays:
String iStr = "Pramoda";
String iStr1 = "ramodaP";

char[] cArray1 = iStr.toCharArray();
char[] cArray2 = iStr1.toCharArray();

Arrays.sort(cArray1);
Arrays.sort(cArray2);

System.out.println("Equal - " + Arrays.equals(cArray1, cArray2));
Output: 
Equal - true

public class Transaction {
public String date;
public int amount;
public String locaiton;

public Transaction(String date, int amount, String location){
this.date = date;
this.amount = amount;
this.locaiton = location;
}

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public int getAmount() {
return amount;
}

public void setAmount(int amount) {
this.amount = amount;
}

public String getLocaiton() {
return locaiton;
}

public void setLocaiton(String locaiton) {
this.locaiton = locaiton;
}
}
List<Transaction> lTrans = List.of(
new Transaction("2025-09-14", 100, "USA"),
new Transaction("2025-09-13", 110, "Ind"),
new Transaction("2025-09-12", 100, "CAN"),
new Transaction("2025-09-12", 110, "USA"),
new Transaction("2025-09-12", 100, "CAN")
);

//Get all transaction for each day
Map<String, List<Integer>> traDateAmountMap = lTrans.stream()
.collect(Collectors
.groupingBy(
Transaction::getDate,
Collectors.mapping(Transaction::getAmount, Collectors.toList())
)
);
System.out.println("Transaction date and all amount for the day - "+traDateAmountMap);
Output:
Transaction date and all amount for the day - 
{2025-09-14=[100], 2025-09-13=[110], 2025-09-12=[100, 110, 100]}
Q. List out date and transactions for a given collection of transactions:
Map<String, List<Transaction>> mTrans = lTrans
.stream()
.collect(Collectors
.groupingBy(Transaction::getDate)
);

System.out.println("Transaction date and all transaction for the day - "+mTrans);
Output:
Transaction date and sum of amount - 
{2025-09-14=[Transaction@6e6c3152], 2025-09-13=[Transaction@50b494a6], 
2025-09-12=[Transaction@3cef309d, Transaction@32709393, Transaction@3d99d22e]}
List<Integer> nList = List.of(2,4,8,15,11,2,11);
int nthValue = 3;
int value = nList
.stream()
.skip(nthValue - 1).findFirst()
.get();

System.out.println("Nth element - "+value);
Output:
Nth element - 8
Q. Find the last element from a given integer collection (List doesn't have a method to find last element):
List<Integer> nList = List.of(2,4,8,15,11,2,11);
Integer element = nList
.stream()
.skip(nList.size() - 1)
.findFirst().get();

System.out.println("Last element - "+element);
Output:
Last element - 11
List<Integer> numList = List.of(2,4,8,15,11,2,11);
Set<Integer> numSet = new HashSet<>();
List<Integer> dupElements = numList
.stream()
.filter(a -> !numSet
.add(a))
.collect(Collectors.toList());

System.out.println("Duplicate elements - "+dupElements);
Output:
Duplicate elements - [2, 11]

Comments

Popular posts from this blog

Functional Programming

Null check of Object and Object Chain in Java