In this tutorial, We will discuss top Java 8 coding and programming interview questions and answers using Stream API functions.
1. Given a list of integers, find out all the even numbers that exist in the list using Stream functions?
import java.util.stream.*;
public class EvenNumberTest{
list.stream()
.filter(n -> n%2 == 0)
.forEach(System.out::println);
}
}
Output:
20, 80, 18, 36
2. Given a list of integers, find out all the numbers starting with 1 using Stream functions?
import java.util.stream.*;
public class NumberStartingWithOneTest{
List<Integer> myList = Arrays.asList(100,99,35,20,15);
myList.stream()
.map(s -> s + "") // Convert integer to String
.filter(s -> s.startsWith("1"))
.forEach(System.out::println);
}
}
Output:
100, 15
3. How to find duplicate elements in a given integers list in java using Stream functions?
import java.util.stream.*;
public class DuplicateElements {
public static void main(String args[]) {
List<Integer> myList = Arrays.asList(20,15,18,25,98,98,32,15);
Set<Integer> set = new HashSet();
myList.stream()
.filter(n -> !set.add(n))
.forEach(System.out::println);
}
}
Output:
98, 15
4. Given the list of integers, find the first element of the list using Stream functions?
import java.util.stream.*;
public class FindFirstElement{
List<Integer> myList = Arrays.asList(15,8,98,32,18);
myList.stream()
.findFirst()
.ifPresent(System.out::println);
}
}
Output:
15
5. Given a list of integers, find the total number of elements present in the list using Stream functions?
import java.util.stream.*;
public class FindTheTotalNumberOfElements{
List<Integer> myList = Arrays.asList(10,25,98,15,8,49,98,32);
long count = myList.stream()
.count();
System.out.println(count);
}
}
Output:
8
6. Given a list of integers, find the maximum value element present in it using Stream functions?
import java.util.stream.*;
public class FindMaxElement{
List<Integer> myList = Arrays.asList(25,8,49,25,88,88,32,25);
int max = myList.stream()
.max(Integer::compare)
.get();
System.out.println(max);
}
}
Output:
88
7. Given a String, find the first non-repeated character in it using Stream functions?
import java.util.stream.*;
import java.util.function.Function;
public class FirstNonRepeated{
String input = "Java articles are Awesome";
Character result = input.chars() // Stream of String
.mapToObj(s -> Character.toLowerCase(Character.valueOf((char) s)))
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1L)
.map(entry -> entry.getKey())
.findFirst()
.get();
System.out.println(result);
}
}
Output:
j
8. Given a String, find the first repeated character in it using Stream functions?
import java.util.stream.*;
import java.util.function.Function;
public class FirstRepeated{
String input = "Java Articles are Awesome";
Character result = input.chars() // Stream of String
// First convert to Character object and then to lowercase
.mapToObj(s -> Character.toLowerCase(Character.valueOf((char) s)))
//Store the chars in map with count
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1L)
.map(entry -> entry.getKey())
.findFirst()
.get();
System.out.println(result);
}
}
Output:
a
9. Given a list of integers, sort all the values present in it using Stream functions?
import java.util.stream.*;
import java.util.function.Function;
public class SortValues{
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
myList.stream()
.sorted()
.forEach(System.out::println);
}
}
Output:
8
10
15
15
25
32
49
98
98
11. Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
List<Integer> list = Arrays.stream(nums)
.boxed()
.collect(Collectors.toList());
Set<Integer> set = new HashSet<>(list);
if(set.size() == list.size()) {
return false;
}
return true;
}
Input: nums = [1,2,3,1]
Output: true
Input: nums = [1,2,3,4]
Output: false
12. How will you get the current date and time using Java 8 Date and Time API?
//Used LocalDate API to get the date
System.out.println("Current Local Date: " + java.time.LocalDate.now());
//Used LocalTime API to get the time
System.out.println("Current Local Time: " + java.time.LocalTime.now());
//Used LocalDateTime API to get both date and time
System.out.println("Current Local Date and Time: " + java.time.LocalDateTime.now());
}
}
13. Write a Java 8 program to concatenate two Streams?
import java.util.List;
import java.util.stream.Stream;
public class Java8 {
List<String> list1 = Arrays.asList("Java", "8");
List<String> list2 = Arrays.asList("explained", "through", "programs");
// Concatenated the list1 and list2 by converting them into Stream
Stream<String> concatStream = Stream.concat(list1.stream(), list2.stream());
// Printed the Concatenated Stream
concatStream.forEach(str -> System.out.print(str + " "));
}
}
14. Java 8 program to perform cube on list elements and filter numbers greater than 50.
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
15. Write a Java 8 program to sort an array and then convert the sorted array into Stream?
public class Java8 {
public static void main(String[] args) {
int arr[] = { 99, 55, 203, 99, 4, 91 };
Arrays.parallelSort(arr);
/* Converted it into Stream and then print using forEach */
Arrays.stream(arr).forEach(n -> System.out.print(n + " "));
}
}
16. How to use map to convert object into Uppercase in Java 8?
public static void main(String[] args) {
List<String> nameLst = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(nameLst);
}
}
output:
AA, BB, CC, DD
17. How to convert a List of objects into a Map by considering duplicated keys and store them in sorted order?
public class TestNotes {
List<Notes> noteLst = new ArrayList<>();
noteLst.add(new Notes(1, "note1", 11));
noteLst.add(new Notes(2, "note2", 22));
noteLst.add(new Notes(3, "note3", 33));
noteLst.add(new Notes(4, "note4", 44));
noteLst.add(new Notes(5, "note5", 55));
noteLst.add(new Notes(6, "note4", 66));
Map<String, Long> notesRecords = noteLst.stream()
// sorting is based on TagId 55,44,33,22,11
.sorted(Comparator.comparingLong(Notes::getTagId).reversed())
// consider old value 44 for dupilcate key and it keeps order
.collect(Collectors.toMap(Notes::getTagName, Notes::getTagId,
(oldValue, newValue) -> oldValue,LinkedHashMap::new));
System.out.println("Notes : " + notesRecords);
}
}
18. How to count each element/word from the String ArrayList in Java8?
List<String> names = Arrays.asList("AA", "BB", "AA", "CC");
Map<String,Long> namesCount = names
.stream()
.collect( Collectors.groupingBy( Function.identity() , Collectors.counting() ));
System.out.println(namesCount);
}
}
Output:
{CC=1, BB=1, AA=2}
19. How to find only duplicate elements with its count from the String ArrayList in Java8?
List<String> names = Arrays.asList("AA", "BB", "AA", "CC");
Map<String,Long> namesCount = names
.stream().filter(x->Collections.frequency(names, x)>1)
.collect(Collectors.groupingBy (Function.identity(), Collectors.counting()));
System.out.println(namesCount);
}
}
Output:
{AA=2}
20. How to check if list is empty in Java 8 using Optional, if not null iterate through the list and print the object?
.orElseGet(Collections::emptyList)
.stream().filter(Objects::nonNull)
.map(note -> Notes::getTagName)
21. Write a Program to find the Maximum element in an array?
return Arrays.stream(arr).max().getAsInt();
}
Input: 12,19,20,88,00,9
output: 88
22. Write a program to print the count of each character in a String?
Map<String, Long> map = Arrays.stream(s.split(""))
.map(String::toLowerCase)
.collect(Collectors
.groupingBy(str -> str, LinkedHashMap::new, Collectors.counting()));
}
Input: String s = "string data to count each character";
Output: {s=1, t=5, r=3, i=1, n=2, g=1, =5, d=1, a=5, o=2, c=4, u=1, e=2, h=2}
23: Find the second largest number in a list of integers using stream?
24: Remove the duplicate elements of a given list using stream.
25 : Find the sum of all the elements of a list using stream.
26: Find the Max/Min of a List using stream.
27: Find the average of a given list of floating-point list using stream.
28: Write a program to check if all the elements are satisfied with a given condition or not?
Example to check if the whole list has even numbers.
29: Find out all the duplicate numbers on a given list and print them using stream.
30: Find the square of the first three even numbers in a given list using stream.
31: Concatenate all the string of a given list of string using stream.
32: Count the number of strings in a given, which starts with a specific character.
32: Write a program to remove duplicate words in a given string using stream
33: Write a program to count words frequency in a given string using stream
34: Given a list of names, group them by their first letter, and then count the number of names in each group.
35: How do you merge two integer arrays into a single sorted array using stream API
36: Concatenate two list of strings & remove duplicates using stream API
Ans: 1. List<String> list1 = List.of("apple", "banana", "orange", "pinaaple"); List<String> list2 = List.of("banana", "kiwi", "grape", "guava", "apple"); Stream.concat(list1.stream(), list2.stream()). distinct(). forEach(System.out::println); 2. List<String> list1 = Arrays.asList("apple","hina","banana","didi","didi"); List<String> list2 = Arrays.asList("singh","hina","banana","didi","didi"); List<String> collect = Stream.concat(list1.stream(),list2.stream())37: Filter all the palindrome words of a list using stream
38: Partition a list of numbers into two groups: even and odd, using a stream
39: Sort a list of custom objects based on a specific attribute for example,
sort a list of employees by employee name using a stream.
package com.javahubpoint;
public class Employee {
Integer empId;
String empName;
Long salary;
Integer deptId;
public Employee(Integer empId, String empName, Integer deptId) {
super();
this.empId = empId;
this.empName = empName;
this.deptId = deptId;
}
public Employee(Integer empId, String empName) {
this.empId = empId;
this.empName = empName;
}
public Employee(Integer empId, String empName, Long salary) {
super();
this.empId = empId;
this.empName = empName;
this.salary = salary;
}
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public Long getSalary() {
return salary;
}
public void setSalary(Long salary) {
this.salary = salary;
}
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ",
salary=" + salary + ", deptId=" + deptId + "]";
}
}
40: How to sort Employees by Name and Salary using stream
41: How to group Employees by department using stream
42: Find and print all the employees who belongs to a particular dept using stream
43 : Student Grade Classification - if a student secured 60 and above mark then "PASS" otherwise "FAIL "
public class Student {
String stdName;
Integer stdMark;
public String getStdName() {
return stdName;
}
public void setStdName(String stdName) {
this.stdName = stdName;
}
public Integer getStdMark() {
return stdMark;
}
public void setStdMark(Integer stdMark) {
this.stdMark = stdMark;
}
@Override
public String toString() {
return "Student [stdName=" + stdName + ",
stdMark=" + stdMark + "]";
}
public Student(String stdName, Integer stdMark) {
super();
this.stdName = stdName;
this.stdMark = stdMark;
}
}
List<Student> stdList = Arrays.asList(new Student("Aditya Sahoo", 50),
new Student("Kiran Panda",80),
new Student("Anand Mishra", 30),
new Student("Dillip Kumar",60));
Map<String, List<Student>> result = stdList.stream()
.collect(Collectors.groupingBy(std->
std.stdMark > 60 ? "PASS":"FAIL"));
System.out.println(result);
44: How to sort a Map based on keys or values using stream
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Dillip", 40);
map.put("Bikash", 20);
map.put("Kiran", 30);
map.put("Aditya", 80);
//sorting a map based on key
System.out.println("sorting a map based on key");
map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(System.out::println);
//sorting a map based on Value
System.out.println("sorting a map based on value");
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(System.out::println);