Java 8 Stream API Commonly Asked Interview Questions
Stream APIs - Streaming API enables streaming of events using push technology and provides a subscription mechanism for receiving events in near real time. The Streaming API subscription mechanism supports multiple types of events, including PushTopic events, generic events, platform events, and change data capture events.
Benefits of Stream APIs - Stream conveys elements from a source, such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations.
Create java class Student.java
Overview of the Student Class
The Student class represents a student with several attributes:
It includes getters and setters for these fields and a constructor to initialize a Student object.
Main Method Breakdown
Here's a detailed explanation of what each part of the main method does:
package com.thelearninghubs.stream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;
public class Student {
private int id;
private String firstName;
private String lastName;
private int age;
private String gender;
private String departmantName;
private int joinedYear;
private String city;
private int rank;
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
public String getDepartmantName() {
return departmantName;
}
public int getJoinedYear() {
return joinedYear;
}
public String getCity() {
return city;
}
public int getRank() {
return rank;
}
public void setId(int id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setAge(int age) {
this.age = age;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setDepartmantName(String departmantName) {
this.departmantName = departmantName;
}
public void setJoinedYear(int joinedYear) {
this.joinedYear = joinedYear;
}
public void setCity(String city) {
this.city = city;
}
public void setRank(int rank) {
this.rank = rank;
}
public Student(int id, String firstName, String lastName, int age, String gender, String departmantName,
int joinedYear, String city, int rank) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
this.departmantName = departmantName;
this.joinedYear = joinedYear;
this.city = city;
this.rank = rank;
}
@Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", gender=" + gender + ", departmantName=" + departmantName + ", joinedYear=" + joinedYear + ", city=" + city + ", rank=" + rank + "]";
}
public static void main(String[] args) {
List<Student> studlist = Arrays.asList(
new Student(1, "Rohit", "Kumar", 30, "Male", "Mechanical Engineering", 2015, "Mumbai", 122),
new Student(2, "Pulkit","Singh", 56, "Male", "Computer Engineering", 2018, "Delhi", 67),
new Student(3, "Ankit", "Patil", 25, "Female","Mechanical Engineering", 2019, "Kerala", 164),
new Student(4, "Satish","Malag", 30, "Male", "Mechanical Engineering", 2014, "Kerala", 26),
new Student(5, "Roshan", "Mukd", 23, "Male", "Biotech Engineering", 2022, "Mumbai", 12),
new Student(6, "Chetan", "Star", 24, "Male", "Mechanical Engineering", 2023, "Karnataka", 90),
new Student(7, "Arun", "Vittal", 26, "Male", "Electronics Engineering", 2014, "Karnataka", 324),
new Student(8, "Nam", "Dev", 31, "Male", "Computer Engineering", 2014, "Karnataka", 433),
new Student(9, "Sonu","Shankar", 27, "Female","Computer Engineering", 2018, "Karnataka", 7),
new Student(10,"Shubham","Pandey", 26, "Male", "Instrumentation Engineering", 2017, "Mumbai", 98)
);
This initializes a list of Student objects with sample data.
2. Find Students Whose First Name Starts with 'A':
List<Student> studentNameA = studlist.stream().filter(s -> s.getFirstName().startsWith("A")).collect(Collectors.toList());
System.out.println("List of students whose name starts with letter A : " + studentNameA);
Filters students whose first names start with the letter 'A' and collects them into a list.
3.Group Students by Department Name:
Map<String, List<Student>> departMentList = studlist.stream()
.collect(Collectors.groupingBy(Student::getDepartmantName));
System.err.println("Group of the student department" + departMentList);
Groups students by their department names and stores the result in a Map.
4. Count the Total Number of Students:
long count = studlist.stream().count();
System.out.println("Count of student :" + count);
Counts the total number of students in the list.
5. Find the Maximum Age:
OptionalInt maxAge = studlist.stream().mapToInt(Student::getAge).max();
System.out.println("Max Age ::" + maxAge.getAsInt());
Finds the maximum age among the students. Uses OptionalInt to handle the case where the list might be empty.
领英推荐
6. Find All Unique Department Names:
List<String> lstDepartments = studlist.stream()
.map(Student::getDepartmantName) .distinct().collect(Collectors.toList());
System.out.println("List of department : " + lstDepartments);
Extracts and lists all unique department names.
7. Count Students in Each Department:
Map<String, Long> countStudentEachDepartment = studlist.stream()
.collect(Collectors.groupingBy(Student::getDepartmantName, Collectors.counting()));
System.out.println("::::Student in each department:::::" + countStudentEachDepartment);
8. Find Students Below Age 30:
List<Student> lessAge30 = studlist.stream()
.filter(s -> s.getAge() < 30) .collect(Collectors.toList());
System.out.println("List of below 30Age " + lessAge30);
Filters students who are younger than 30.
9. Find Students with Rank Between 50 and 100:
List<Student> rankList = studlist.stream()
.filter(st -> st.getRank() > 50 && st.getRank() < 100)
.collect(Collectors.toList());
System.out.println("::::::student list between rank 50 to 100::::::::::" + rankList);
10. Average Age of Male and Female Students:
Map<String, Double> mapAvgAge = studlist.stream()
.collect(Collectors.groupingBy(Student::getGender, Collectors.averagingInt(Student::getAge)));
System.out.println(":::average age of male and female::::" + mapAvgAge);
11. Find Department with Maximum Number of Students:
Entry<String, Long> entry = studlist.stream()
.collect(Collectors.groupingBy(Student::getDepartmantName, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue()).get();
System.out.println(":::Maximum number of students in which department" + entry);
12. Find Students in Delhi and Sort by Name:
List<Student> studentLocation = studlist.stream()
.filter(dt -> dt.getCity().equals("Delhi"))
.sorted(Comparator.comparing(Student::getFirstName))
.collect(Collectors.toList());
System.out.println("::tays in Delhi and sort them by their names::" + studentLocation);
13. Average Rank in Each Department:
Map<String, Double> collect = studlist.stream()
.collect(Collectors.groupingBy(Student::getDepartmantName, Collectors.averagingInt(Student::getRank)));
System.out.println("Average rank in all departments : " + collect);
14. Find the Highest Rank (Lowest Value) in Each Department:
Map<String, Optional<Student>> studentData = studlist.stream()
.collect(Collectors.groupingBy(Student::getDepartmantName,
Collectors.minBy(Comparator.comparing(Student::getRank))));
System.out.println("Highest rank in each department : " + studentData);
15. Sort Students by Rank:
List<Student> stuRankSorted = studlist.stream()
.sorted(Comparator.comparing(Student::getRank))
.collect(Collectors.toList());
System.out.println("List of students sorted by their rank : " + stuRankSorted);
16. Find the Student with the Second Highest Rank:
Student student = studlist.stream()
.sorted(Comparator.comparing(Student::getRank)).skip(1) .findFirst() .get();
System.out.println("Second highest rank student : " + student);
Finds the student with the second highest rank by sorting students and skipping the first one.
The code demonstrates various operations using Java Streams to manipulate and analyze a list of Student objects. These operations include filtering, grouping, counting, and sorting, which are fundamental tasks when working with collections in Java. The code also showcases how to handle optional values and perform statistical calculations like averages.
You're welcome! I'm glad I could help with the explanation. If you have any more questions about Java, streams, or any other topic, feel free to ask. Happy coding! https://thelearninghubs.in