Java 8 - Questions & Answers

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.*;
import java.util.stream.*;

public class EvenNumberTest{
    public static void main(String args[]) {

      List<Integer> list = Arrays.asList(20,15,80,49,25,18,36);
            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.*;
import java.util.stream.*;

public class NumberStartingWithOneTest{
    public static void main(String args[]) {

            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.*;
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.*;
import java.util.stream.*;

public class FindFirstElement{
  public static void main(String args[]) {

          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.*;
import java.util.stream.*;

public class FindTheTotalNumberOfElements{
  public static void main(String args[]) {

          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.*;
import java.util.stream.*;

public class FindMaxElement{
  public static void main(String args[]) {

          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.*;
import java.util.stream.*;
import java.util.function.Function;

public class FirstNonRepeated{
  public static void main(String args[]) {

    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:

j


8. Given a String, find the first repeated character in it using Stream functions?

import java.util.*;
import java.util.stream.*;
import java.util.function.Function;

public class FirstRepeated{
  public static void main(String args[]) {

          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.*;
import java.util.stream.*;
import java.util.function.Function;

public class SortValues{
  public static void main(String args[]) {

          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


10. Given a list of integers, sort all the values present in it in descending order using Stream functions?

import java.util.*;
import java.util.stream.*;
import java.util.function.Function;

public class SortDescending{
  public static void main(String args[]) {

          List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);

           myList.stream()
                 .sorted(Collections.reverseOrder())
                 .forEach(System.out::println);
  }
}

Output:

98
98
49
32
25
15
15
10
8

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.

public boolean containsDuplicate(int[] nums) {

    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?

class Java8 {
    public static void main(String[] args) {

//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.Arrays;
import java.util.List;
import java.util.stream.Stream;
 
public class Java8 {
    public static void main(String[] args) {
 
        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.

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

15. Write a Java 8 program to sort an array and then convert the sorted array into Stream?

import java.util.Arrays;
public class Java8 {
    public static void main(String[] args) {

        int arr[] = { 99, 55, 203, 99, 4, 91 };
   // Sorted the Array using parallelSort()
        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 class Java8 {
 
    public static void main(String[] args) {

        List<String> names = Arrays.asList("aa", "bb", "cc", "dd");
        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 {
    public static void main(String[] args) {

    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?

public class TestNotes {
    public static void main(String[] args) {

        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?

public class TestNotes {
    public static void main(String[] args) {

      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?

Optional.ofNullable(noteLst)

// creates empty immutable list: [] in case noteLst is null
            .orElseGet(Collections::emptyList) 

//loop throgh each object and consider non null objects
            .stream().filter(Objects::nonNull) 

// method reference, consider only tag name
            .map(note -> Notes::getTagName) 

 // it will print tag names
            .forEach(System.out::println);

21. Write a Program to find the Maximum element in an array?

public static int findMaxElement(int[] arr) {
  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?

public static void findCountOfChars(String s) {

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?

Ans: -

List nums = Arrays.asList(5, 7, 3, 9, 11, 2,9);
  int result=nums.stream().
     distinct().
      sorted(Comparator.reverseOrder()).
       skip(1).
        findFirst().get();
  System.out.println(result);

Output - 11

24: Remove the duplicate elements of a given list using stream.

Ans:
List<Integer> nums = Arrays.asList(5, 4, 3, 9, 3, 4);
nums.stream().
distinct().
forEach(System.out::println);
Output - 5,4,3,9

25 : Find the sum of all the elements of a list using stream.

Ans:
List<Integer> nums = Arrays.asList(5, 7, 3, 9, 11, 2);
int result=nums.stream().
mapToInt(Integer:: intValue)
.sum();
System.out.println(result);

26: Find the Max/Min of a List using stream.

Ans:
List<Integer> nums = Arrays.asList(5, 7, 3, 9, 11, 2, 6);
int min=nums.stream().
mapToInt(Integer:: intValue).
min().getAsInt();
System.out.println(min);

int max=nums.stream().
mapToInt(Integer:: intValue).
max().getAsInt();
System.out.println(max);

27: Find the average of a given list of floating-point list using stream.

Ans:
List<Double> nums = Arrays.asList(5.1, 7.2 ,4.2, 3.0, 9.9, 14.7, 11.9, 2.6);
double average= nums.stream().
mapToDouble(Double::doubleValue)
.average().getAsDouble();
System.out.println(average);

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.

Ans:

Example1 - to check if the whole list has all even numbers.
List<Integer> nums = Arrays.asList(2, 4, 8, 3, 14, 16);
boolean allEven=nums.stream().allMatch(n->n%2==0);
System.out.println(allEven);

Example1 - to check if the whole list has any even number.
List<Integer> nums = Arrays.asList(3, 13, 11);
boolean anyEven=nums.stream().anyMatch(n->n%2==0);
System.out.println(anyEven);


29: Find out all the duplicate numbers on a given list and print them using stream.

Ans:
List<Integer> nums = Arrays.asList(5,0,7, 4, 2, 13, 9, 14, 11, 7, 9, 14);
nums.stream().
filter(n->Collections.frequency(nums, n)>1).
collect(Collectors.toSet()).
forEach(System.out::println);

30: Find the square of the first three even numbers in a given list using stream.

Ans:
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
nums.stream().
filter(n->n%2==0). 
limit(3).
map(i->i*i).
forEach(System.out::println);


31: Concatenate all the string of a given list of string using stream.

Ans:
List<String> fruits = Arrays.asList("Apple", "Banana","Guava","cherry","coconut","Berry");
String concatenatedString=fruits.stream().collect(Collectors.joining("::"));
System.out.println(concatenatedString);

32: Count the number of strings in a given, which starts with a specific character. 

Ans:
List<String> fruits = Arrays.asList("Apple", "Banana","Guava","cherry","coconut","Berry");
long count=fruits.stream().filter(e->e.startsWith("B")).count();
System.out.println(count);

32: Write a program to remove duplicate words in a given string using stream 

Ans:
String s= "This is java language and java is versatile language";
Arrays.stream(s.split(" ")).distinct().forEach(System.out::println);

33: Write a program to count words frequency in a given string using stream

Ans:
1.Map<String, Long> wordFrequency=Arrays.stream(str.split(" ")).
collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()));
System.out.println(wordFrequency);
2.String str = "this is demo but because this is my first program";
Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(a->a,Collectors.counting()))
.forEach((key,value)->{
System.out.println(key+" :: "+value);
});;

34: Given a list of names, group them by their first letter, and then count the number of names in each group.

Ans:
1. String[] names = { "Anand", "Bipin", "Rakesh", "Abhi", "Rohan", "Akash", "Ravi", "Sima" };
Map<Character, Long> result = Arrays.stream(names)
.collect(Collectors.groupingBy(s -> s.charAt(0), Collectors.counting()));
System.out.println(result);

2. List<String> list = Arrays.asList("apple","aakash","arya","yogi","yoga","yogita","hina","himani");
list.stream().collect(Collectors.groupingBy(a->a.charAt(0),Collectors.counting())).forEach((a,b)->{
System.out.print(a+" :: ");
System.out.println(b);
});

35: How do you merge two integer arrays into a single sorted array using stream API

Ans:
1. int[] array1 = { 1, 3, 32, 5, 7 };
int[] array2 = { 2, 4, 6, 62, 8 };
IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).
sorted().
forEach(System.out::println);
2.
List<Integer> list1 = Arrays.asList(1,2,3,4,5,6);
List<Integer> list2 = Arrays.asList(7,8,9,10,55);
Stream.concat(list1.stream(), list2.stream()))
.forEach(System.out::println);

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())
.distinct().collect(Collectors.toList()); System.out.println(collect);

37: Filter all the palindrome words of a list using stream

Ans: String[] str = { "abc", "ada", "kiran", "level", "apple", "narendra", "madam" }; Arrays.stream(str). filter(s -> new StringBuilder(s).reverse().toString().equals(s)) .forEach(e -> System.out.println(e));

38: Partition a list of numbers into two groups: even and odd, using a stream

Ans:
List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Map<Boolean, List<Integer>> result = nums.stream()
                    .collect(Collectors.partitioningBy(n->n%2==0));
System.out.println(result);

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.

Ans:

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 + "]";

}


}

List<Employee> empList = Arrays.asList(new Employee(101, "Narendra Modi"), new Employee(102, "Kiran Panda"), new Employee(103, "Anand Mishra"), new Employee(104, "Dillip Kumar")); //Sort using empName. Default is ascending order empList.stream().sorted(Comparator.comparing(Employee::getEmpName))
                                  .forEach(e -> System.out.println(e)); //Sort using empName. But in descending order empList.stream().sorted(Comparator.comparing(Employee::getEmpName,
Comparator.reverseOrder())).forEach(e -> System.out.println(e));


40: How to sort Employees by Name and Salary using stream

Ans:
List<Employee> empList =  Arrays.asList(new Employee(101, "Narendra Modi", 50000), 
    new Employee(102, "Kiran Panda", 80000),
    new Employee(103, "Anand Mishra", 70000),
    new Employee(104, "Kiran Panda", 60000));
//Sort using empName. Default is ascending order
empList.stream().sorted(Comparator.comparing(Employee::getEmpName))
                      .forEach(e -> System.out.println(e));

System.out.println("==========================================");

// In the above employees are sorted based on name. If we want to order by name and salary then we have to write code like below

empList.stream().sorted(Comparator.comparing(Employee::getEmpName)
                                  .thenComparing(Employee::getSalary))
                                   .forEach(e -> System.out.println(e));

41: How to group Employees by department using stream

Ans:
List<Employee> empList =  Arrays.asList(new Employee(101, "Aditya Sahoo", 10), 
    new Employee(102, "Kiran Panda",20),
    new Employee(103, "Anand Mishra", 10),
    new Employee(104, "Dillip Kumar",30));

Map<Integer, List<Employee>> result = empList.stream()     .collect(Collectors.groupingBy(Employee::getDeptId));
System.out.println(result);


42: Find and print all the employees who belongs to a particular dept using stream

Ans:
List<Employee> empList =  Arrays.asList(new Employee(101, "Aditya Sahoo", 10), 
    new Employee(102, "Kiran Panda",20),
    new Employee(103, "Anand Mishra", 10),
    new Employee(104, "Dillip Kumar",30));
//suppose dept number is 10
empList.stream().filter(emp -> emp.deptId ==10)
                      .forEach(System.out::println);

43 : Student Grade Classification - if a student secured 60 and above mark then "PASS" otherwise "FAIL "

Ans:

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

 Ans:

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);