In this post, we are going to see Java 8 Programming Interview Questions and Answers.
Write a program to find even number from list using Java 8.
import java.util.*;
public class FindEvenNumber{
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(number -> number % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even numbers in the list: " + evenNumbers);
}
}
Output is –
Even numbers in the list: [2, 4, 6, 8, 10]
How to find unique elements from list using Java 8?
You can find unique elements from a list in Java 8 using the Stream API along with the distinct()
operation. Here’s a Java 8 program to do that:
import java.util.*;
public class FindUniqElements{
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5, 6, 6, 7);
List<Integer> uniqueNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("Unique elements in the list: " + uniqueNumbers);
}
}
When you run this program, it will output:
Unique elements in the list: [1, 2, 3, 4, 5, 6, 7]
This demonstrates how to find unique elements from a list using Java 8’s Stream API and the distinct()
operation.
Write a program using Java 8 to print first character of given String.
For example if given string is rakesh then expected output is r
package com.javatute;
public class FindFirstCharacterOfString {
public static void main(String[] args) {
String s1 = "rakesh";// expected o.p-r
char firstChar = s1.chars().mapToObj(c -> (char) c).findFirst().get();
System.out.println(firstChar);
}
}
Output :-
r
The code segment s1.chars().mapToObj(c -> (char) c).findFirst().get();
is used to find and retrieve the first character of the string s1
.
s1.chars()
: This part of the code converts the strings1
into an IntStream of character code points..mapToObj(c -> (char) c)
: After converting the string into an IntStream, we use themapToObj
operation to map each integer (Unicode code point) back to its corresponding character using the(char)
casting. So, we convert the IntStream of character code points back into a Stream of characters.
Write a program to find duplicate elements from list using Java 8.
Consider we have list of integers. List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5, 6, 6, 7);
Expected output is – [2,4,6]
package com.javatute;
import java.util.*;
import java.util.stream.Collectors;
public class FindDuplicateElements {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5, 6, 6, 7);
// expected output is - [2,4,6]
Set<Integer> finalList = new HashSet<>();
numbers.stream().filter(n -> !finalList.add(n))
.collect(Collectors.toSet()).forEach(System.out::println);
}
}
Output is –
[2, 4, 6]
.filter(n -> !finalList.add(n))
– This is a filter operation applied to each element in the stream. It uses a lambda expressionn -> !finalList.add(n)
as the filter condition. Here’s how it works:
- For each element
n
in the stream, it checks ifn
can be added to thefinalList
(which is a HashSet). Theadd
method of a Set returnstrue
if the element was successfully added (i.e., it was not already present in the set), andfalse
if the element was already present in the set. - The
!
(negation) operator is used to reverse the result. So, if!finalList.add(n)
istrue
, it means thatn
is already infinalList
, indicating a duplicate element. If!finalList.add(n)
isfalse
, it means thatn
is not infinalList
, indicating a unique element. - Therefore, the
filter
operation keeps only the elements for which!finalList.add(n)
istrue
, effectively filtering out the unique elements.
How to convert String to Map object using Java 8 where Character should be Map’s key and number of repetition will be Map’s value?
How to find sum of elements present in array using java 8.
package com.javatute;
import java.util.Arrays;
import java.util.List;
public class SumOfElementsOfArray {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 4, 3, 5,6,7);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println(sum);
}
}
Output is – 28
How to find nth highest salary from an Employee object?
Write a program using Java 8 that converts a List to a Map.
Write a program using Java 8 to print repeated characters and the number of repetitions.
Write a program to sort an employee list on the basis of their salary.
How to get top three highest salaried employees.
Consider we have Employee class that contains three attributes id, name and salary. Write a program to find three employee those having highest salary.
package com.javatute;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Employee {
private int id;
private String name;
private double salary;
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", salary=" + salary + '}';
}
}
public class GetHighestThreeSalaryEmployee {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(new Employee(1, "John", 75000.0), new Employee(2, "Alice", 80000.0),
new Employee(3, "Bob", 70000.0), new Employee(4, "Eva", 90000.0), new Employee(5, "Mike", 85000.0));
List<Employee> topThreeHighestSalariedEmployees = employees.stream()
.sorted((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary())) // Sort by salary in descending
// order
.limit(3) // Limit to the top three employees
.collect(Collectors.toList());
System.out.println("Top Three Highest Salaried Employees:");
topThreeHighestSalariedEmployees.forEach(System.out::println);
}
}
Output is –
Top Three Highest Salaried Employees:
Employee{id=4, name='Eva', salary=90000.0}
Employee{id=5, name='Mike', salary=85000.0}
Employee{id=2, name='Alice', salary=80000.0}