Java 8 Stream API Commonly Asked Interview Questions
www.thelearninghubs.in

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.

  • Offers high performance.
  • Enables innovative automations.
  • Fosters greater employee productivity.
  • Reduces human errors.
  • Improves the employer's reputation.
  • Enhances the customer experience.


The Learning Hub
www.thelearninghubs.in


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

  1. Creating a List of Students:

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


要查看或添加评论,请登录

Osihar Kumar Yadav的更多文章

  • Securing Your Spring Boot Application: A Comprehensive Guide

    Securing Your Spring Boot Application: A Comprehensive Guide

    Security is a critical aspect of web application development. Spring Boot, a powerful and versatile framework, makes it…

    2 条评论
  • Reflecting on Java's Evolution: A Journey Through 2024

    Reflecting on Java's Evolution: A Journey Through 2024

    As the sun sets on 2024, it's the perfect moment to reflect on the milestones and advancements in the world of Java…

  • Overview of database keys with examples to illustrate each type

    Overview of database keys with examples to illustrate each type

    KEYS in DBMS is an attribute or set of attributes which helps you to identify a row(tuple) in a relation(table). They…

  • What is the Singleton Design Pattern

    What is the Singleton Design Pattern

    The Singleton Design Pattern is a creational design pattern that ensures a class has only one instance and provides a…

  • Stream API in Java

    Stream API in Java

    The Stream API is a powerful feature introduced in Java 8 that allows for functional-style operations on sequences of…

  • SQL Interview Questions

    SQL Interview Questions

    1. What is SQL? SQL means Structured Query Language and is used to communicate with relational databases.

    1 条评论
  • API Gateway in Spring Boot (MICROSERVICES)

    API Gateway in Spring Boot (MICROSERVICES)

    APIs are a common way of communication between applications. In the case of microservice architecture, there will be a…

    1 条评论
  • Explain the working of microservice architecture.

    Explain the working of microservice architecture.

    Microservice Architecture consists of the following components: Client: Initiates requests and interacts with the…

    1 条评论
  • Java Homogenous or Heterogenous types

    Java Homogenous or Heterogenous types

    In Java, "heterogeneous" and "homogeneous" typically refer to collections, such as arrays or lists, and how they handle…

  • Explain the internal working of Spring Boot.

    Explain the internal working of Spring Boot.

    spring boot Spring Boot is a framework built on top of the Spring framework that aims to simplify the process of…

社区洞察

其他会员也浏览了