In this tutorial we will look all the java 8 programs for interview. Please book mark this page because I will keep adding questions to it.
Lets begin…
Generally an array or a List can only be converted to a stream. If you are having a HashMap object, you have to convert that to a Set first before creating a stream out of it.
Given the below data, answer the questions that followed:
int[] intArr={1,2,3,4}; List<Integer> intList=Arrays.asList(1,2,3,4); List<String> courses=Arrays.asList("Spring","Spring Boot","API","Microservices","AWS"); Map<String,Integer> map=new HashMap<>(); map.put("bb", 45); map.put("aa", 77); map.put("cc", 60); List<Employee> empList=new ArrayList<>(); empList.add(new Employee("Prasanna", 45, 15000)); empList.add(new Employee("Padma", 77, 25000)); empList.add(new Employee("Sarojini", 77, 10000));
@Data @AllArgsConstructor @NoArgsConstructor class Employee{ String name; int age; double salary; }
Question : How to create a stream ?
Ans: Below are the 3 ways to create a stream:
Arrays.stream(intArr); Stream.of(intArr); intList.stream();
Question: What is Sequential stream ?
Ans:
In Sequential streams a task is run using a single core, just like in a for-loop.
By default, any stream operation in Java is processed sequentially, unless explicitly specified as parallel.
intList.stream().forEach(x -> System.out.println(x + ":" + Thread.currentThread().getName()));
Output of the above code:
1:main 2:main 3:main 4:main
Question: What is Parallel stream ?
Ans:
In Parallel stream a task is divided into multiple sub-task and is executed by multiple threads in multiple cores of the computer.
intList.parallelStream().forEach(x -> System.out.println(x + ":" + Thread.currentThread().getName()));
Output of the above code:
3:main 4:main 1:main 2:ForkJoinPool.commonPool-worker-1
One more way to create a parallel stream:
Arrays.stream(intArr).parallel().forEach(System.out::println);
Question: Print the list elements using Lambda expressions ?
Ans:
intList.stream().forEach(s -> System.out.println(s));
Question: Print the list elements using Method Reference ?
Ans:
intList.stream().forEach(System.out::println);//Method Reference
Question: Print all the elements from the map object ?
Ans: To convert a map to stream first you have to convert the map to EntrySet object.
map.entrySet().stream().forEach(System.out::println);
Question: Print only even numbers ?
Ans:
intList.stream().filter(x -> x%2==0).forEach(System.out::println); //Lambda Expresson used
Question: Print the courses having the string “Spring” ?
Ans:
courses.stream().filter(x -> x.contains("Spring")).forEach(System.out::println);
Question: Print the courses having more than 3 characters ?
Ans:
courses.stream().filter(x -> x.length()>3).forEach(System.out::println);
Question: Generate a list of courses having more than 3 characters ?
Ans:
List list=courses.stream().filter(x -> x.length() > 3).collect(Collectors.toList());
Question: Print the square of numbers ?
Ans:
intList.stream().map(s -> s*s).forEach(System.out::println);
Question: Print the squares of even numbers ?
Ans:
intList.stream().filter(s -> s%2==0).map(s -> s*s).forEach(System.out::println);
Question: Print the max of the numbers in the list ?
Ans: You can use either of the 2 way:
int max=intList.stream().max((x,y) -> x - y).get(); System.out.println("Max number: "+ max);
Or:
int max=intList.stream().max(Comparator.comparing(Integer::intValue)).get(); System.out.println("Max number: "+ max);
Question: Given a list of employees, print the employee who is having the highest salary ?
Ans: You can use either of the below ways:
Employee e=empList.stream().max(Comparator.comparing(Employee::getSalary)).get(); System.out.println(e.name);
Or:
Employee e=empList.stream().max((x,y) -> (int)x.salary - (int)y.salary).get(); System.out.println(e.name);
Question: Find out the employees whose age is 45 ?
Ans:
empList.stream().filter(x -> x.age == 45).forEach(System.out::println);
Question: Print the no. of characters in each course name ?
Ans:
courses.stream().map(s -> s.length()).forEach(System.out::println);
The best way to learn functional programming is by making our hands dirty. And, do some “unlearning” of the Structural programming.
P.S.: “Unlearning” does not mean “Forgetting”.
Lets do some complex operations like reduce(), distinct(), sorted() etc.:
Question: Add all the numbers in the list ?
Ans: You can use either of the below way:
System.out.println(intList.stream().reduce((x,y)-> x+y).get());
System.out.println(intList.stream().reduce(0, (x,y)-> x+y));
In the above reduce(), the first param is 0, that means the starting value is 0 which will be added to the first element, then the sum will be added to next element, and this goes on till the last element. Here x represents the “aggregate” value and y represents the “next value”.
Or you can use below code, as Integer has an sum method:
System.out.println(intList.stream().reduce(0, Integer::sum));
Question: What is the output of below code?
System.out.println(intList.stream().reduce(0, (x,y)-> x));
Answer: 0
Why ? Here 0 will be added to the first element and the result should be first element that is 0. Then 0 will be added to the next element and the result will be x that is 0. This keeps continuing to the last element and the final result should be 0.
Question: And what is the output of below ?
System.out.println(intList.stream().reduce(0, (x,y)-> y));
Answer: 4
Question: And what is the output of below ?
System.out.println(intList.stream().reduce(0, (x,y)-> x>y ? x:y));
Answer: 4
Square every number in the list and find the sum of it:
System.out.println(intList.stream().map(x -> x*x).reduce(0, (x,y)-> x+y));
Question :How to Find sum of odd numbers in the list ?
Ans:
System.out.println(intList.stream().filter(x -> x%2 != 0).reduce(0, (x,y)-> x+y));
Question: How to remove the duplicate elements from the list ?
Ans:
intList.stream().distinct().forEach(System.out::println);
Question: There is one more way to do the above task ?
Ans:
intList.stream().collect(Collectors.toSet()).forEach(System.out::println);
Question: Given a list of employees, print the employee name having the 2nd highest salary ?
Ans:
String name= empList.stream().sorted((x,y) -> (int)y.salary - (int)x.salary).collect(Collectors.toList()).get(1).getName(); System.out.println(name);
Question: How to print the elements in a ascending order ?
Ans:
intList.stream().sorted().forEach(System.out::println);
A Task for you: How to print the elements in sorted and distinct ?
Question: How to print the elements in ascending order based on string length ?
Ans: You can used either of the below two commands:
courses.stream().sorted((x,y)-> x.length()-y.length()).forEach(System.out::println); courses.stream().sorted(Comparator.comparing(String::length)).forEach(System.out::println); courses.stream().sorted(Comparator.comparing(x -> x.length())).forEach(System.out::println);
Question: Print the items of a map object in ascending order ?
Ans: You can use either of the below 3 statements:
map.entrySet().stream().sorted((x,y) -> x.getKey().compareTo(y.getKey()) ).forEach(System.out::println); map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(System.out::println); map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).forEach(System.out::println);
Question: Print the items of a map object in ascending order of Value ?
Ans: You can use either of the below way:
map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println);
Or:
map.entrySet().stream().sorted((x,y) -> x.getValue().compareTo(y.getValue())).forEach(System.out::println);
And if you want to collect it to a map:
Map result = map.entrySet().stream().sorted((x,y) -> x.getValue().compareTo(y.getValue()) ).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
Question: What is flat map ?
Ans:
Given below 2D array, its difficult to print the items in it unless we flatten it to a Single dimensional array. So for that we need flatMap():
Integer[][] intArray2D = new Integer[][]{{1, 2}, {3, 4}};
So, first you need to convert the above to a stream, then flatten it to another stream of single dimension stream:
Stream<Integer[]> stream = Arrays.stream(intArray2D); stream.flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
You can combine the above 2 lines of code to one line like below:
Integer[][] intArray2D = new Integer[][]{{1, 2}, {3, 4}};
P.S.: In the above example we had not used primitive int, we had used the Integer class type. Better not to use any primitive type in streams as streams is all about streaming objects.
Question: Count the no. of alphabets in a String ?
Ans:
String str="abc"; System.out.println(str.chars().count());
Question: Write your own Functional Interface and use it using Lambda
Answer: Below is the code where we had created our own Functional Interface and used it using a Lambda expression:
@FunctionalInterface interface Addition{ public int add(int a, int b); } public class Manager { public static void main(String[] args) { Addition addition= (x,y) -> x+y; System.out.println(addition.add(5,6)); } }
Question: Find duplicate elements in a given integers list ?
Ans:
Set set=new HashSet(); intList.stream().filter(x -> !set.add(x)).forEach(System.out::println);
Question: Given a list of integers, find out all the numbers starting with 1 using Stream functions ?
Ans:
list.stream().map(x -> x.toString()).filter(x -> x.startsWith("1")).forEach(System.out::println);
Question: Given a list of integers, sort all the values present in it in descending order using Stream functions ?
Ans:
list.stream().sorted((x,y) -> y-x ).forEach(System.out::println);
Question: Given a list of String, convert object to Uppercase ?
Ans:
courses.stream().map(x -> x.toUpperCase()).forEach(System.out::println);
Java 8 Collectors: groupingBy()
Question: count the characters in each String in the List of Strings ?
Ans: You can use either of the below way:
courses.stream() .collect(Collectors.groupingBy( x -> x, Collectors.mapping(x -> x.length(), Collectors.toList()) ));
output:
{API=[3], Spring Boot=[11], Spring=[6], AWS=[3], Microservices=[13]}
Or
Map map5=courses.stream().collect(Collectors.toMap( //x -> x, String::length x -> x, (x -> x.length()) ));
output:
{Spring Boot=11, API=3, Spring=6, AWS=3, Microservices=13}
Question: Group the employees based on age ?
Ans: You can use either of the below command:
Map<Integer,List<Employee>> map=empList.stream() .collect(Collectors.groupingBy( x -> x.getAge() ));
Or:
Map<Integer,List<Employee>> map=empList.stream() .collect(Collectors.groupingBy( Employee::getAge ));
Output: If you print the map object you will get below data:
{77=[Employee(name=Padma, age=77, salary=25000.0), Employee(name=Sarojini, age=77, salary=10000.0)], 45=[Employee(name=Prasanna, age=45, salary=15000.0)]}
If you see, the data is grouped based on age. The output is an HashMap object where the key is age and value is an List of Employee objects.
Now if we don’t want to show the full Employee object, rather only the name, then below is the example:
Question: Group the employees based on age and show only the names of the employee ?
Ans:
Map result = empList.stream() .collect(Collectors.groupingBy( x -> x.age, Collectors.mapping(x -> x.name,Collectors.toList()) )); System.out.println(result);
Output: If you print the map object you will get below data:
{77=[Padma, Sarojini], 45=[Prasanna]}
Question: Count the number of employees in each age ?
Ans: You can use either of the below way:
Map result = empList.stream() .collect(Collectors.groupingBy( x -> x.age, Collectors.mapping(x -> x,Collectors.counting()) )); System.out.println(result);
Or:
Map result = empList.stream() .collect(Collectors.groupingBy( x -> x.age, Collectors.counting() )); System.out.println(result);
Output:
{77=2, 45=1}
Question: Suppose we want to create LinkedHashMap object, instead of the default HashMap ?
Map result = empList.stream() .collect(Collectors.groupingBy( x -> x.age, LinkedHashMap::new, Collectors.counting() )); System.out.println(result);
LinkedHashMap::new – this means you are using the constructor of LinkedHashMap.
Output:
{45=1, 77=2}
As you can see groupingBy() have 3 overloaded methods. The signature of the above used groupingBy() is like below:
public static <T,K,D,A,M extends Map<K,D>> Collector<T,?,M> groupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)
Question: Give the below integer array, write a program to count the frequency of each numbers ?
{12,0,9,8,2,1,0,2,1,4,1}
Ans: While creating the array create a Integer array instead of int array, else you will get complications while processing:
Integer[] intArr = {12,0,9,8,2,1,0,2,1,4,1}; Map result = Arrays.stream(intArr).collect(Collectors.groupingBy( x -> x, Collectors.counting() )); System.out.println(result);
Question: Given a String, write a program to print the count of each character in a String ?
Ans: First you have to convert the String to a Stream, then you have to work on it:
String s = "Java is my favourite language"; Map result = Arrays.stream(s.split("")) .collect(Collectors.groupingBy( x -> x, Collectors.counting() )); System.out.println(result);
Output:
{ =4, a=5, e=2, f=1, g=2, i=2, j=1, l=1, m=1, n=1, o=1, r=1, s=1, t=1, u=2, v=2, y=1}
Question: Given a String, find the first non-repeated character in it using Stream functions ?
Ans: This example is an continuation of the above example. I had given inline comments:
String s = "Java is my favourite language"; String result = Arrays.stream(s.split("")) //split converts a String to String[], which then converted to a Stream. .map(x -> x.toLowerCase()) //convert every object in the Stream to lower case. .collect(Collectors.groupingBy(x -> x, LinkedHashMap::new, Collectors.counting())) //store it in a LinkedHashMap object where key would be the object and value would be its count. .entrySet()//again try to create another Stream, since its a HashMap object this is the way to create a stream out of it. .stream() .filter(x -> x.getValue() == 1) // filter out all objects having value 1 .map(x -> x.getKey()) // convert those objects to stream of Keys which are basically the character objects .findFirst() //fetch the first object .get(); System.out.println(result);
Output:
j
One more way:
String result=Arrays.stream(s.split("")) .collect(Collectors.groupingBy(x -> x, LinkedHashMap::new, Collectors.counting())) .entrySet().stream() .filter(x -> (!x.getKey().equals(" ") && x.getValue()== 1)) .toList() .get(0).getKey(); System.out.println(result);
Question : Given a list of Students, assign the sections as per the starting alphabet of a Student :
A-O -> A section
P-Z -> B Section
Ans:
Map result = names.stream() .collect(Collectors.groupingBy( x -> x.charAt(0) <= 'O' ? 'A':'B' )); System.out.println(result);
Output:
{A=[Hena, Muhammed, Anitha], B=[Punith, Rajput, Vimal, Rama]}
Question: How to check if list is empty in Java 8 using Optional, if not null iterate through the list and print the object?
Ans:
Optional.ofNullable(intList).stream().forEach(System.out::println);
Question: Reverse a string using streams ?
Ans:
String str ="prasanna123"; String result = Arrays.stream(str.split("")) .reduce("", (x, y) -> y + x); System.out.println(result);
Question: Reverse a string excluding the numbers using streams ?
Ans:
String str ="prasanna123"; //reverse the character except the numbers. String result = Arrays.stream(str.split("")) .filter(s -> !s.matches("[0-9]")) .reduce("", (x, y) -> y + x); System.out.println(result);
Question: Print the lowest string length in the courses String array?
Ans:
int min = courses.stream() .mapToInt(x -> x.length()) .min().getAsInt(); System.out.println(min);