Saravanan's Corner: Blackberry Dev

Friday, 11 July 2025

Tricky Streams


//How many male and female employees are there in the organization?

//Print the name of all departments in the organization?

//What is the average age of male and female employees?

//Get the details of highest paid employee in the organization? 

//Count the number of employees in each department?

//What is the average salary of each department?

//Get the details of youngest male employee in the product development department?

//Who has the most working experience in the organization?

//How many male and female employees are there in the sales and marketing team?

//What is the average salary of male and female employees?

//List down the names of all employees in each department?

//What is the average salary and total salary of the whole organization?

//Query 3.14 : Separate the employees who are younger or equal to 25 years from those employees who are older than 25 years.



//Find the occurance of each chars in the string

String input = "Saravanan";

Map<String, Long> map = Arrays.stream(input.split("")).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));


// Find all duplicate element from a given string

List<String> list = Arrays.stream(input.split("")).collect(Collectors.groupingBy(s -> s, Collectors.counting()))

.entrySet().stream().filter(s -> s.getValue() > 1).map(Map.Entry :: getKey).collect(Collectors.toList());


// Find the unique elements from a given string

list = Arrays.stream(input.split("")).collect(Collectors.groupingBy(s -> s, Collectors.counting())).entrySet()

.stream().filter(s -> s.getValue() == 1).map(Map.Entry::getKey).collect(Collectors.toList());

// Find first non repeated elements from a given string

list = Arrays.stream(input.split("")).collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()))

.entrySet().stream().filter(s -> s.getValue() == 1).map(Map.Entry::getKey).collect(Collectors.toList());

System.out.print(list);

//Find second highest number from given array

int[] numbers = {5,9,11,2,8,21,1};

int highestNo = Arrays.stream(numbers).boxed().sorted(Comparator.reverseOrder()).skip(1).findFirst().get().intValue();


// find longest string from given array

String[] array1 = { "saranasdasd", "raja", "mani", "saran1" };

String strngIs = Arrays.stream(array1)

.reduce((string1, string2) -> string1.length() > string2.length() ? string1 : string2).get();

System.out.print(strngIs);

// find all elements from array who starts with 1

int[] numbers3 = { 5, 9, 11, 2, 8, 21, 1 };

Arrays.stream(numbers).boxed().map(s -> s + "").filter(s -> s.startsWith("1")).collect(Collectors.toList())

.forEach(System.out::println);


//String join method

List<String> s = Arrays.asList("1", "2", "3", "4");

System.out.println(String.join(",", s));


//Sort a list and Map





. `**filter**` 

*Question:* Fetch all numbers from a list that are greater than 5.


`**map**` 

*Question:* Transform a list of strings into a list of their uppercase versions


`**flatMap**` 

*Question:* Given a list of lists of strings, flatten them into a single list of strings.


`**distinct**` 

*Question:* Remove duplicates from a list of integers.


`**sorted**` 

*Question:* Sort a list of names in reverse alphabetical order.


`**peek**` 

*Question:* Print each element in a list while converting them to uppercase.


`**limit**` 

*Question:* Fetch the first 3 elements from a list of integers.


`**skip**` 

*Question:* Skip the first 4 elements and fetch the remaining elements from a list of integers.


`**forEach**` 

*Question:* Print each element of a list of strings with a prefix "Item: ".


`**collect**` 

*Question:* Collect a list of integers into a `Set`.


`**reduce**` 

*Question:* Compute the product of all numbers in a list.


`**allMatch**` 



The `allMatch` method in Java Streams is used to check if all elements in the stream satisfy a given predicate. It returns `true` if every element in the stream matches the predicate, and `false` otherwise.


*Short-Circuiting:* The `allMatch` operation is short-circuiting, meaning it stops processing as soon as it finds the first element that does not match the predicate. If it finds such an element, it immediately returns `false`.




*Question:* Check if all numbers in a list are positive.



`**anyMatch**` 

The `anyMatch` method checks whether *at least one element* in the stream matches a given predicate. It returns `true` as soon as it finds an element that satisfies the predicate and stops further processing. If no elements match, it returns `false` 




`anyMatch` is short-circuiting, meaning it stops processing as soon as it finds the first element that matches the predicate, optimizing performance.


`**noneMatch**` 



The `noneMatch` method in Java Streams is used to check if *no elements* in the stream match a given predicate. It returns `true` if none of the elements satisfy the predicate and `false` if at least one element does.


 Like `allMatch` and `anyMatch`, `noneMatch` is short-circuiting. It stops processing as soon as it finds the first element that matches the predicate and immediately returns `false` 




*Question:* Check if no elements in a list are negative.


`**findFirst**` 

 is used to retrieve the *first element* in a stream that matches a given condition or simply the first element in the stream if no filtering is applied. It returns the first element wrapped in an `Optional`, which is a container object that may or may not contain a non-null value.


Threads

 Q) What is MultiTasking And Its types. In java interview question and Answers


Performing  multiple tasks at one time . There are 2 types of multitasking :

Process based multitasking

Thread based multitasking


Q) What is Multi threading & how is it diff from multi tasking asked In java interview question and Answers


 Multithreading is a specialized form of multitasking.


Process-based multitasking is executing several tasks simultaneously where each task is a separate independent process is Process-based multitasking . 

For example, process based multitasking enables you to run the Java IDE at the same time that you are using a text editor or visiting a web site using chrome.


Thread-based multitasking is executing several tasks simultaneously where each task is a separate independent part of the same program (called Thread).

For instance,JUnit uses threads to run test cases in parallel. As an application, you can have computer games. You see objects in games like cars, motor bikes etc. They are just threads that run in the game application.




Q)  Which is better process based multitasking or thread based multitasking and why is one of the most asked java interview question and Answers?

 Thread based multitasking is better.


Multitasking threads require less overhead than multitasking processes. 


Processes are heavyweight tasks that require their own separate address spaces. 


Threads, on the other hand, are lighter weight. They share the same address space and cooperatively share the same heavyweight process. 


Interprocess communication is expensive and limited. Context switching from one process to another is also costly.


Q)  Which is better process based multitasking or thread based multitasking and why?

Inter Thread communication is inexpensive, and context switching from one thread to the next is lower in cost. 


While Java programs make use of process-based multitasking environments, process-based multitasking is not under Java’s direct control. However, multithreaded multitasking is. 


Q) What is a Thread


Threads are light-weight processes within a process.

Java creates threads by using a "Thread Class".


 All Java programs have at least one thread, known as the main thread, which is created by the Java Virtual Machine (JVM) at the program’s start, when the main() method is invoked with the main thread.


Q) Types of Thread in java


There are two types of thread – user thread and daemon thread.



Q) How to create a user thread in Java

 Thread implementation in java can be achieved in two ways:


Extending the java.lang.Thread class

Implementing the java.lang.Runnable Interface



When the JVM starts, it creates a thread called “Main”. Your program will run on this thread, unless you create additional threads yourself. The first thing the “Main” thread does is to look for your static void main (String args[]) method and invoke it. That is the entry-point to your program. If you create additional threads in the main method those threads would be the child threads of main thread.


Thread priority - 1 to 10

defult priority for main thread is 5

Daemon thread is low priority thread

Exception Handling Java Q

 Q) What is an exception?

The exception is an abnormal condition that occurs during the execution of a program and disrupts the normal flow of the program. If not handled properly it can cause the program to terminate abruptly.


 Q) How do we handle exceptions in Java

Try

Encloses set of statements which can throw exception hence are required to be monitored.


Catch

When exception occur, this block catches that exception and work accordingly to handle it or to throw it as required.


Finally

This block gets executed always regardless of exception occurrence. Hence clean up is done here. 


Q) Difference between Exception VS Error

Exception

We can recover from exception using try catch block or using throw

Compiler will have knowledge about checked Exceptions hence Compiler will force you to use try-catch blocks

Exceptions are related to application

Exceptions include both checked as well as unchecked type.

Exceptions in java are of type java.lang.Exception.


Error

Recovering from Error is not possible

Compiler will not have any knowledge about unchecked exceptions and  Errors

Errors are related to environment where  application is running 

All errors in java are unchecked type

Errors in java are of type java.lang.Error.


Q) Can we write only try block without catch and finally blocks?

No. either catch or finally is must.


if no  then what error will come?


Answer : compile time error saying “insert finally to complete try statement” like this:


Q) Can we write any other statements between try catch or finally block?

No. Try must be followed directly by either catch or finally.


Q) Does remaining statements in try block executes after exception occurs.

No. if exception occurs at a particular point in try block then all statements after that statement where exception is occurred will not be execute and the flow goes directly to either catch block if there is any or else program terminates. Hence we need finally block to do all clean up like closing files or removing locks.


Q) What Is the Difference Between Throw and Throws Keywords in Exception Handling in java?.

Throw 

Java throw keyword is used to explicitly throw an exception.

Checked exception cannot be propagated using throw only.

Throw is used within the method.

You cannot throw multiple exceptions.


Throws

Java throws keyword is used to 

declare an exception.

Checked exception can be propagated with throws.

Throws is used with the method signature.

You can declare multiple exceptions.


Q) What Happens When an Exception Is Thrown by the Main Method?


When an exception is thrown by main() method, Java Runtime terminates the program and prints the exception message and the stack trace in-system console.


Q) What do you understand by unreachable catch block error.

This error comes when you keep super classes first and sub classes later. Like here We kept Exception which is parent of NullPointer Exception first.


Hence the order of catch blocks must be from most specific to most general ones. 

Problem Solving Interview - Java

 1) Remove duplicates from string and return in same order".


String s = "dabfcadef"; -> dabfce



s.chars().distinct().mapToObj( c-> (char)  c ).forEach(System.out::println);


Arrays.stream(s.split("")).distinct().forEach(System.out::print);



2)  Given a sentence find the word that has the highest length. The solution is:


String s = "I am interested123455 to grow in my organization";


     String maxString = Arrays.stream(s.split(" ")).max(Comparator.comparing(String::length)).get();

     System.out.println("The maxString is: " + maxString);


3) Given a sentence find the word that has the 2nd (Nth) highest length.


Answer is below: skip(N). N =0 (highest) N =1 (2nd Highest) N =2 (3rd Highest...)


String a =  Arrays.stream(s.split("")).sorted(Comparator.comparing(String::length).reversed()).skip(1).findFirst().get();


 System.out.println(a);


This question asked in SNP. They will tweak the same question with list of Employee Objects. But this is the base logic.



Q4) Find the length of the longest word


Solution : Arrays.stream(s.split(" ")).mapToInt(l -> l.length()).max().getAsInt();


Q5). Find the 2nd highest length word in the given sentence


Solution : Arrays.stream(s.split(" ")).map(l -> l.length()).sorted(Comparator.reverseOrder()).skip(1).findFirst().get();



Q6) Given a sentence, find the number of occurrence of each word.




String input = "the quick brown fox jumps right over the little lazy dog little";

            Map<String, Long> collect = Arrays.stream(input.split(" "))

                           .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

            System.out.println(collect);


Q7) Given a word, find the occurrence of Each Character


Q8) There is a list of Employees and Employee object has a field called e-mail. Find the list of domains ( gmail.com, yahoo.com..) and the no of occurrences for each domain.


Q9) Given a string, find the words with the maximum number of vowels.


       "The quick brown fox jumps right over the little lazy dog."

        Maximum Number of Vowels: 2

        output Words: quick, over, little  ( because each word has maximum of 2 vowels)




Solution is:


String s = "The quick brown fox jumps right over the little lazy dog.";

        Arrays.stream(s.split(" "))

            .filter(e -> e.replaceAll("[^aeiouAEIOU]", "").length() == 2)

            .forEach(System.out::println);




NOTE: Please understand the REGEX solution here



Q10) Reverse a string with speical characters and Speical characters position shouldn't be changed".




Solution is:




 public static String reverseString(String input) {


        String reversedString = new StringBuffer(input.replaceAll("[^a-zA-Z]", "")).reverse().toString();

        String replacedString = input.replaceAll("[a-zA-Z]", "_");


        char ch[] = reversedString.toCharArray();

        for(char c:ch) {

            replacedString = replacedString.replaceFirst("_", String.valueOf(c));

        }

        System.out.println("-------> " + replacedString);

        return replacedString;

    }



public static void main(String[] args) {

           String input = "Swa$pn&il";

            String[] arr = input.split("");

            String regex = "[^0-9a-zA-Z]";


            StringBuilder reversed=new StringBuilder(input.replaceAll(regex, "")).reverse();


            IntStream.range(0, input.length()-1)

            .filter(i->arr[i].matches(regex))

            .forEach(i->reversed.insert(i, arr[i]));


            System.out.println(reversed);

    }



Q11) Given a list of integers, divide into two lists one having even numbers and other having odd numbers.



Solutions:


 List<List<Integer>> lists = intList.stream()

        .collect(Collectors.groupingBy(key->key%2==0,Collectors.toList()))

        .entrySet().stream().map(e->e.getValue()).collect(Collectors.toList());

        System.out.println(lists);


2. intList.stream()

                .collect(Collectors.partitioningBy(integerValue->integerValue%2==0))

                .entrySet().stream().map(mapValue->mapValue.getValue()).collect(Collectors.toList());


3. Map<Boolean, List<Integer>> partitions = ints.stream()

                .collect(Collectors.partitioningBy(x -> x % 2 == 0));

        List<Integer> evens = partitions.get(true);

        List<Integer> odds = partitions.get(false);

The entryset logic in solution 1 and 2 is to process the map. and also please know the difference between partitionBy and groupBy and when to use.




Q12) Given an array of integers (2, 34, 54, 23, 33, 20, 59, 11, 19, 37 ) group the numbers by the range they belong to. The put put should be {0=[2], 50=[54,59], 20=[23,20], 10=[11,19], 30=[34,33,37]}


Solution is:

Map<Integer, List<Integer>> map = 

 Stream.of(2, 34, 54, 23, 33, 20, 59, 11, 19,37).collect(Collectors.groupingBy (i -> i/10 * 10 )); 

                System.out.println(map);



Q13) Given a List of Strings  ["as", "123", "32", "2as"], create another Integer list that contains only integers. The output shoul be: List<Integer> iList = [123,32]

Solution:

 listOfStrings.stream().filter( ss -> ss.matches("[0-9]*")).map(Integer::valueOf).collect(Collectors.toList());



Q14) Given an array of integers arr = {5,6,7,8,5,5,8,8,7) find the sum of the unique elements. The output should be in this case is: 26.


Solution : Arrays.stream(arr).distinct().sum();



Q15 ) Given a numeric array , re arrange the elements to form a smallest possible value.


input is: int arr[] = {1, 34, 3, 98, 9, 76, 45, 4};


output is: 133444576998


Solution is: Arrays.stream(arr).mapToObj(i-> i+"").sorted().forEach(System.out::print);



Q16) Given a numeric array , re arrange the elements to form a highest possible value.


input is: int arr[] = {1, 34, 3, 98, 9, 76, 45, 4};


output is: 998764543431



Solution is: Arrays.stream(arr).mapToObj(i-> i+"").sorted((o1,o2) -> (o2+o1).compareTo(o1+o2)).forEach(System.out::print)



2) Arrays.stream(arr12).mapToObj(i-> i+"").sorted(Collections.reverseOrder()).forEach(System.out::print); ( solution is wrong. Associates need to fix it).



Q17)  Given a String = The quick brown fox jumps over the lazy dog, find the first non repeated character. (Google interview)



Solution with java 8 :


String res = Arrays.stream(str.split("")).filter(c -> str.indexOf(c) == str.lastIndexOf(c)).findFirst().get();

System.out.println(res);




______________________________________________________________________________________________________________________________________________________________________________

1) Find the longest word in a sentence?


Input: I am interested to grow in my organization

output is: organization


2) Find the lenght of the longest word.


Input: I am interested to grow in my organization

output is: 12


3) Find the 2nd highest length in the sentence.


4) FInd the length of the 2nd longest word.



5) List of cities


"Mumbai"

"Munnar"

"chennai"

"Hyderabad"


Calcullate the lenght of each city where the city name starts with 'm' or 'M' and create a list.



Can you  write a program to create another list that contains the cities start with "m"?



6)  I have to arrays

int arr1[] = {21,6,8,9,10,5};

int arr2[] = {10,21,5,8,6,9};


write a program to check whether both arrays are equal or not.


7)  Given a string, find the words with the maximum number of vowels.


"The quick brown fox jumps right over the little lazy dog."

Maximum Number of Vowels: 2


output Words: quick, over, little  ( because each word has maximum of 2 vowels)


8)  I have an array.  Find the next greatest element for each element in a given array.


   {15, 10, 16, 20, 8, 9, 7, 50}


   OutPut:


   15 -16

   10 -16

   16-20

   20-50

   8-9

   9-50

   7-50

   50 - Max Integer


   Solution : 

           int[] intArray = {15, 10, 16, 20, 8, 9, 7, 50};


           for (int i = 0; i < intArray.length; i++) {

            for (int j = i + 1; j < intArray.length; j++) {

                if (intArray[j] > intArray[i]) {

                    System.out.println(intArray[i] + " - " + intArray[j]);

                    break;

                }

            }

        }

        System.out.println(intArray[intArray.length - 1] + " - Max Integer");


9) I have two sorted arrays. Need to merge those.



10) A List<String> contains alpha, numeric and alpha numeric values as strings. Write a program to create a List<Integer>s from the original List.


input :  List <String> ls =  ["as", "123", "32", "2as"]

output : List<Integer> iList = [123,32]



11) How to remove duplicates from an arrayList?



12) I have a passenger Object. that has an e-mail.  So given the list of passenger Objects

I need to find the list of domains and the no of times each domain occured.




13)


Student class 

sting name

string subject

int marks

List of student

student - A - hindi - 50

student - A - maths - 90

student - A - science - 70


student - B - hindi - 80

student - B - maths - 90

student - B - science - 70

output - 

student a hindi 50 (least for student A)

student a maths 90 (hightest for student A)


student b scice 70 (least for student b)

student b maths 90 (hightest for student b)




14)


Left Rotate array :


[28-07 04:44 pm] Anurag Prajapati

input : 1 2 3 4 5 6

number: 3 -

output: 4 5 6 1 2 3




Work on recursion problems.


15. Fibonacci series.


Input: N = 10

Output: 0 1 1 2 3 5 8 13 21 34


Input: N = 15

Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377




16. Permutations from a string.


Input is: ABC

Output is:

ABC ACB

BAC BCA

CBA CAB


17. Reversal program with special characters.


Input : Swa$pn&il

Output : lin$pa&wS




98413211 47




1)


Given 2 numbers as list, add the numbers and store the result in a new list.

2->3->5->7->NULL

8->2->7->NULL

Output : 3->1->8->4->NULL


2) [04-08 02:08 pm] Damodara Gottipalli

Input Array is: {15, 10, 16, 20, 8, 9, 7, 50 }


[04-08 02:08 pm] Damodara Gottipalli

   15 -16

   10 -16

   16-20

   20-50

   8-9

   9-50

   7-50

   50 -1


[04-08 02:13 pm] Damodara Gottipalli

Find the next greatest element for each element in the Array.




3)



Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference.


Input : A[] = {l, 3, 15, 11, 2}

        B[] = {23, 127, 235, 19, 8}


Output : 3

the pair is: 11, 8









insertion sort.

quick sort

selection sort

merge sort

bubble sort.




100)

For a given string, like "aabbccdeff", count each char and declare winner or loser by following rules

· Winner char will have max number of char count and no other char will have same count

· Loser will have min number of char count and no other char will have same count.

Input: aabbccdeff

Output: winner: none, loser: e



101)

The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.


https://www.geeksforgeeks.org/java-program-for-stock-buy-sell-to-maximize-profit/



SQL - Index

What are Indexes and How to create an index in SQL? you will always face this as most asked sql interview questions


Indexes are database objects which help in retrieving records quickly and more efficiently. Column indexes can be created on both Tables and Views. By declaring a Column as an index within a table/ view, the user can access those records quickly by executing the index. Indexes with more than one column are called Clustered indexes.


Syntax:CREATE INDEX INDEX_NAME ON TABLE_NAME(COL1, COL2);

The syntax to drop an Index is DROP INDEX INDEX_NAME on TABLE_NAME;


Indexes are known to improve the efficiency of SQL Select queries

Suppose we need to search by employee name = Manoj

What goes on behind the scenes is  Every single row is checked to see if the employee_name matches with Manoj. This effectively means that the entire table will have to be scanned (known as the full table scan).


An index is a data structure that stores the values for a certain specific column of a table and helps us avoid a full table scan. 


Database Indexing in reality, allows us to cut down the number of rows/records that need to be examined when a select query with a where clause is executed.


Few DS are :

B-tree - Database indexes will also store pointers which are simply reference information for the location of the additional information in memory.  Basically the index holds the company_id and that particular row’s home address on the memory disk.


The query looks for the specific row in the index; the index refers to the pointer which will find the rest of the information.


Index takes up additional space, so the larger the table, the bigger the index. 

Every time you perform an add, delete, or update operation, the same operation will need to be performed on the index as well.


 If we drop a table, does it also drop related objects like constraints, indexes, columns, default, views and stored procedures?


Yes, SQL server drops all related objects, which exists inside a table like constraints, indexex, columns, defaults etc. 


But dropping a table will not drop views and sorted procedures as they exist outside the table.  

Thursday, 10 July 2025

MUST Interview Questions


*Q) How do you monitor your spring boot application on prod?*


*Q) What is service discovery? Why do you need multiple Eurekas?*


*Q) What is circuit breaker DP?*


*Q) How do you handle transactions across multiple microservices?*


*Q) How do microservices communicate with each other?*


*Q) Explain the architecture of Kafka.*


*Q) How did you implement Kafka in your project?*


*Q) What is Zookeeper in Kafka? Can Kafka be used without Zookeeper?*


*Q) What do you mean by ISR in Kafka environment?*


*Q) What is consumer lag?*


*Q) What is marking the offset as soon as you read the message from Kafka broker?*


*Q) How did you implement synchronous communication between microservices?*


*Q) You have implemented some REST endpoints for CRUD functionality, how will you share your contract with clients/other teams?*


*Q) How did you implement security end to end?*


*Q) Why Docker?*


*Q) K8 commands you used?*


*Q) How do you analyze logs of pods in your project?*


*Q) Explain the difference between a Pod and a Container in Kubernetes.*


*Q) What is the difference between CI and CD?*


*Q) Explain steps you used in CI/CD in your project.* 

Kafka interview Questions

Apache Kafka is a key tool in today’s world of data and distributed systems. It’s widely used for real-time data streaming and processing, making it an important skill for many tech roles like software engineers, data engineers, and DevOps professionals. As more companies adopt real-time data solutions, having Kafka expertise has become highly valuable.


This Kafka interview preparation guide covers more than 70 mostly asked Kafka interview questions, from Kafka's basic concepts to its architecture and best practices. By reviewing these questions and answers, you will be able to show your understanding of Kafka and how it works in real-world scenarios, giving you a solid edge in your interviews.


List of 70 Kafka Interview Questions with Answers

1. What is Apache Kafka?

Apache Kafka is a distributed streaming platform that allows for publishing, subscribing to, storing, and processing streams of records in real-time. It's designed to handle high-throughput, fault-tolerant, and scalable data pipelines. Kafka is often used for building real-time data pipelines and streaming applications.


2. What are the key components of Kafka?

The key components of Kafka include:


Producer: Publishes messages to Kafka topics.

Consumer: Subscribes to topics and processes the published messages.

Broker: A Kafka server that stores and manages topics.

ZooKeeper: Manages and coordinates Kafka brokers.

Topic: A category or feed name to which records are published.

Partition: Topics are divided into partitions for scalability.

3. What is a topic in Kafka?

A topic in Kafka is a category or feed name to which records are published. Topics in Kafka are always multi-subscriber; that is, a topic can have zero, one, or many consumers that subscribe to the data written to it. Topics are split into partitions for improved scalability and parallel processing.


4. What is a partition in Kafka?

A partition is an ordered, immutable sequence of records that is continually appended to. Each partition is a structured commit log, and records in the partitions are each assigned a sequential id number called the offset. Partitions allow Kafka to scale horizontally and provide parallel processing capabilities.


5. What is the role of ZooKeeper in Kafka?

ZooKeeper is used for managing and coordinating Kafka brokers. It serves as a centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services. ZooKeeper keeps track of the status of Kafka cluster nodes, Kafka topics, and partitions.


6. What is a broker in Kafka?

A broker is a Kafka server that runs in a Kafka cluster. It receives messages from producers, assigns offsets to them, and commits the messages to storage on disk. It also services consumers, responding to fetch requests for partitions and responding with the messages that have been published.


7. How does Kafka ensure fault tolerance?

Kafka ensures fault tolerance through data replication. Each partition is replicated across a configurable number of servers for fault tolerance. One of the servers is designated as the leader, which handles all read and write requests for the partition, while the others are followers that passively replicate the leader.


8. What is the difference between a Kafka consumer and consumer group?

A Kafka consumer is an application that reads data from Kafka topics. A consumer group is a set of consumers that work together to consume data from one or more topics. The key difference is that each message is delivered to one consumer instance within each subscribing consumer group. This allows for parallel processing and load balancing of topic consumption.


9. What is the purpose of the offset in Kafka?

The offset is a unique identifier of a record within a partition. It denotes the position of the consumer in the partition. Kafka maintains this offset per partition, per consumer group, allowing each consumer group to read from a different position in the partition. This enables Kafka to provide both queue and publish-subscribe messaging models.


10. How does Kafka handle message delivery semantics?

Kafka supports three message delivery semantics:


At most once: Messages may be lost but are never redelivered.

At least once: Messages are never lost but may be redelivered.

Exactly once: Each message is delivered once and only once. The choice depends on the specific use case and can be configured through producer and consumer settings.

11. What is the role of the Kafka producer API?

The Kafka producer API is used to publish streams of records to Kafka topics. It handles partitioning of messages, compression, and load balancing across multiple brokers. The producer is also responsible for retrying failed publish attempts and can be configured for different levels of delivery guarantees.


12. How does Kafka support scalability?

Kafka supports scalability through partitioning and distributed processing. Topics can be partitioned across multiple brokers, allowing for parallel processing. Consumers can be grouped to read from multiple partitions simultaneously. Brokers can be added to a cluster to increase capacity, and the cluster can be scaled without downtime.


13. What is log compaction in Kafka?

Log compaction is a mechanism to give finer-grained per-record retention, rather than the coarser-grained time-based retention. The idea is to selectively remove records where we have a more recent update with the same primary key. This way, the log is guaranteed to have at least the last state for each key.


14. How does Kafka handle message ordering?

Kafka guarantees order within a partition. Messages sent by a producer to a particular topic partition will be appended in the order they are sent. A consumer instance will read records in the order they are stored in the log. However, there's no guarantee of order across partitions.


15. What is the significance of the acks parameter in Kafka producers?

The acks parameter in Kafka producers controls the number of acknowledgments the producer requires the leader to have received before considering a request complete. It affects the durability of records and can be set to: 0: No acknowledgment 1: Leader acknowledgment only all: Full ISR (In-Sync Replica) acknowledgment


16. How does Kafka handle data retention?

Kafka handles data retention through configurable retention policies. These can be based on time (e.g., retain data for 7 days) or size (e.g., retain up to 1GB per partition). After the retention limit is reached, old messages are discarded. Kafka also supports log compaction for topics where only the latest value for each key is needed.


17. What is the purpose of the Kafka Connect API?

Kafka Connect is a tool for scalably and reliably streaming data between Apache Kafka and other data systems. It makes it simple to quickly define connectors that move large collections of data into and out of Kafka. This can be used to connect Kafka with databases, key-value stores, search indexes, and file systems.


18. How does Kafka ensure high availability?

Kafka ensures high availability through:


Replication of partitions across multiple brokers

Automatic leader election when a broker fails

Ability to add brokers to a cluster without downtime

Configurable number of in-sync replicas for durability

ZooKeeper for distributed coordination and broker management

19. What is the difference between Kafka Streams and Apache Flink?

While both Kafka Streams and Apache Flink are stream processing frameworks, they have some key differences:


Kafka Streams is a client library for building applications and microservices, where the input and output data are stored in Kafka clusters. Flink is a distributed processing engine that can work with various data sources and sinks.

Kafka Streams is tightly integrated with Kafka, while Flink has a more general-purpose design.

Flink generally offers lower latency and higher throughput for complex operations, while Kafka Streams is simpler to deploy and operate.

20. How does Kafka handle message compression?

Kafka supports message compression to reduce the size of data transferred and stored. Compression can be configured at the producer level, and Kafka supports several compression types including gzip, snappy, lz4, and zstd. The broker can be configured to decompress messages to validate and convert them to the message format version on the broker.


21. What is the purpose of the Kafka Streams API?

The Kafka Streams API is a client library for building applications and microservices that process and analyze data stored in Kafka. It enables you to build stream processing applications with just standard Java and Kafka clients, without the need for a separate processing cluster. It supports stateful operations, windowing, joining streams and tables, and more.


22. How does Kafka handle message size limits?

Kafka has configurable message size limits. The default maximum message size is 1MB, but this can be increased by changing the 'message.max.bytes' configuration on the broker and the 'max.request.size' on the producer. However, very large messages can impact performance and memory usage, so it's generally recommended to keep messages relatively small.


23. What is the role of the group coordinator in Kafka?

The group coordinator in Kafka is responsible for managing consumer groups. It handles consumer group membership, assigns partitions to consumers within a group, and manages offset commits. When a consumer joins or leaves a group, the group coordinator triggers a rebalance to reassign partitions among the remaining consumers.


24. How does Kafka handle data replication?

Kafka replicates data by maintaining multiple copies of each partition across different brokers. One broker is designated as the leader for a partition, handling all read and write requests, while others are followers that replicate the leader's data. If a leader fails, one of the followers becomes the new leader. The number of replicas is configurable per topic.


25. What is the purpose of the Idempotent Producer in Kafka?

The Idempotent Producer in Kafka ensures that messages are delivered exactly once to a partition, even in the case of retries. It achieves this by assigning a unique ID to each produce request and maintaining a sequence number for each producer-partition pair. This prevents duplicate messages due to network issues or producer retries.


26. How does Kafka handle consumer offsets?

Kafka maintains offsets for each consumer group per partition. These offsets represent the position of the consumer in the partition log. Consumers can commit these offsets either automatically (at a configurable interval) or manually. Kafka stores these offsets in a special Kafka topic called '__consumer_offsets', allowing consumers to resume from where they left off in case of restarts or failures.


27. What is the difference between a round-robin partitioner and a key-based partitioner in Kafka?

A round-robin partitioner distributes messages evenly across all partitions in a cyclic manner, regardless of any key. A key-based partitioner, on the other hand, uses a hash of the key to determine which partition a message should go to. This ensures that all messages with the same key always go to the same partition, which is crucial for maintaining order for key-based events.


28. How does Kafka handle message deletion?

Kafka doesn't delete messages individually. Instead, it uses a retention policy to manage message deletion. Messages are retained either for a configurable amount of time or until the topic reaches a certain size. Once the retention limit is reached, Kafka deletes messages in bulk by removing whole segments of the log file. For more fine-grained control, Kafka also supports log compaction.


29. What is the purpose of the Kafka Mirror Maker?

Kafka Mirror Maker is a tool used for replicating data between Kafka clusters, potentially across different data centers. It works by consuming from one Kafka cluster and producing to another. This is useful for maintaining a backup of your data, aggregating data from multiple datacenters into a central location, or for migrating data between clusters.


30. How does Kafka handle message versioning?

Kafka itself doesn't handle message versioning directly, but it provides mechanisms that allow users to implement versioning. One common approach is to include a version field in the message schema. For more complex versioning needs, many users leverage schema registries (like the Confluent Schema Registry) which can manage schema evolution and compatibility.


31. What is the role of the controller in a Kafka cluster?

The controller in a Kafka cluster is a broker that has additional responsibilities for managing the overall state of the cluster. It's responsible for electing partition leaders, managing the distribution of partitions across brokers, and handling administrative operations like adding or removing topics. If the controller fails, ZooKeeper helps elect a new controller from among the brokers.


32. How does Kafka ensure data consistency?

Kafka ensures data consistency through several mechanisms:


Replication: Each partition is replicated across multiple brokers.

In-Sync Replicas (ISR): Only replicas that are up-to-date with the leader can be part of the ISR.

Acknowledgments: Producers can be configured to wait for acknowledgments from the leader and ISRs.

Atomic writes: Writes to a partition are atomic and ordered.

Idempotent producers: Prevent duplicate messages in case of retries.

33. What is the purpose of the Kafka AdminClient API?

The Kafka AdminClient API provides administrative operations for managing and inspecting topics, brokers, configurations, and other Kafka objects. It can be used to create, delete, and describe topics, manage ACLs, get cluster information, and perform other administrative tasks programmatically.


34. How does Kafka handle message batching?

Kafka producers can batch messages to improve throughput. Instead of sending each message individually, the producer can group multiple messages destined for the same partition into a single request. This reduces network overhead and improves efficiency. The batch size and linger time (how long to wait for more messages before sending a batch) are configurable.


35. What is the difference between a Kafka consumer and a Kafka streams application?

A Kafka consumer is a client that reads data from Kafka topics and processes it in some way. It's typically used for simple consumption scenarios. A Kafka Streams application, on the other hand, is a more sophisticated client that can consume, process, and produce data back to Kafka. It provides a DSL for complex stream processing operations like filtering, transforming, aggregating, and joining streams.


36. How does Kafka handle message ordering within a partition?

Kafka guarantees that messages within a partition are ordered. Messages sent by a producer to a specific partition will be appended to the log in the order they are sent. Consumers read messages from a partition in the exact order they were written. This ordering guarantee is crucial for use cases that require event sequencing.


37. What is the purpose of the Kafka Transactions API?

The Kafka Transactions API allows for atomic updates to multiple topics and partitions. It enables exactly-once processing semantics for applications that read, process, and write data to Kafka. This is particularly useful for stream processing applications that need to ensure that each input event affects the output exactly once, even in the face of failures.


38. How does Kafka handle message key hashing?

When a key is provided with a message, Kafka uses a hash of the key to determine which partition the message should go to. By default, Kafka uses murmur2 algorithm for key hashing. This ensures that messages with the same key always go to the same partition, which is crucial for maintaining order for key-based events and for enabling local state in stream processing applications.


39. What is the role of the Kafka consumer coordinator?

The Kafka consumer coordinator is responsible for managing the state of the consumer group and coordinating the consumer group rebalance process. It assigns partitions to consumers in the group, ensures that each partition is consumed by only one consumer in the group, and manages the committed offsets for each partition.


40. How does Kafka handle message timestamps?

Kafka supports two types of timestamps:


CreateTime: The time the producer created the message.

LogAppendTime: The time the broker received the message. These timestamps can be used for log retention, log compaction, and time-based search in consumers. The timestamp type is configurable at the topic level.

41. What is the purpose of the Kafka Quota API?

The Kafka Quota API allows you to enforce quotas on produce and fetch requests to prevent a single client from consuming too many broker resources. Quotas can be defined on a per-client or per-user basis, and can limit the rate of data production or consumption. This helps in ensuring fair resource allocation and preventing denial of service scenarios.


42. How does Kafka handle message acknowledgments?

Kafka producers can be configured to require acknowledgments when sending messages. There are three settings:


acks=0: No acknowledgment (fire and forget)

acks=1: Leader acknowledgment only

acks=all: Full ISR (In-Sync Replica) acknowledgment The choice affects the trade-off between latency and durability. Higher levels of acknowledgment provide stronger durability guarantees but increase latency.

43. How does Kafka handle message acknowledgments?

Kafka producers can be configured to require acknowledgments when sending messages. There are three settings:


acks=0: No acknowledgment (fire and forget)

The producer doesn't wait for any acknowledgment from the broker.

This option has the lowest latency but the weakest durability guarantees since the message may be lost if the broker goes down.

acks=1: Leader acknowledgment only

The producer waits for the leader replica to acknowledge the message.

This provides better durability than acks=0, but there's still a risk of message loss if the leader fails immediately after acknowledging but before the followers have replicated the message.

acks=all: Full ISR (In-Sync Replica) acknowledgment

The producer waits for the message to be acknowledged by all in-sync replicas.

This setting provides the strongest durability guarantee but has the highest latency.

The choice of acknowledgment level affects the trade-off between latency and durability. Higher levels of acknowledgment provide stronger durability guarantees but increase latency.


44. How does Kafka handle message serialization and deserialization?

Kafka itself treats message data as opaque byte arrays and doesn't perform any serialization or deserialization. However, Kafka producers and consumers can be configured with serializers and deserializers for keys and values. Common formats include String, Integer, and Avro. For complex objects, custom serializers and deserializers can be implemented.


45. What is the purpose of the Kafka Schema Registry?

The Kafka Schema Registry provides a serving layer for metadata. It provides a RESTful interface for storing and retrieving Avro schemas. It's used in conjunction with Kafka to ensure that producers and consumers use compatible schemas. This is particularly useful in evolving data models over time while maintaining backward and forward compatibility.


46. How does Kafka handle topic deletion?

When a topic is deleted in Kafka, the following steps occur:


The topic is marked for deletion in ZooKeeper

Kafka stops serving data for that topic

The actual log segments on disk are asynchronously deleted This process ensures that topic deletion doesn't impact the performance of other operations. However, it's worth noting that in versions prior to Kafka 2.1, topic deletion could sometimes be incomplete if brokers were offline during the deletion process.

47. What is the difference between a Kafka consumer's poll() and subscribe() methods?

The subscribe() method is used to subscribe a consumer to one or more topics. It doesn't actually fetch any data. The poll() method, on the other hand, is used to fetch data from the subscribed topics. It returns records that have been published since the last fetch for the subscribed topics and partitions. poll() is typically called in a loop to continuously consume data.


48. How does Kafka handle message compression at the broker level?

Kafka brokers can be configured to handle message compression in several ways:


Pass-through: The broker stores the message in its original compressed format

Decompress on receipt: The broker decompresses the message on receipt and stores it uncompressed

Decompress and recompress: The broker decompresses the message and then recompresses it, potentially with a different algorithm The choice depends on factors like CPU usage, network bandwidth, and storage requirements.

49. What is the purpose of the Kafka consumer heartbeat thread?

The Kafka consumer heartbeat thread is responsible for sending periodic heartbeats to the Kafka broker (specifically, to the group coordinator). These heartbeats indicate that the consumer is alive and still part of the consumer group. If a consumer fails to send heartbeats for a configurable period, it's considered dead, and the group coordinator will trigger a rebalance to reassign its partitions to other consumers in the group.


50. How does Kafka handle message ordering across multiple partitions?

Kafka only guarantees message ordering within a single partition. Across multiple partitions, there is no guarantee of message ordering. If global ordering is required, it's typically achieved by using a single partition for the topic, but this limits scalability. For use cases requiring ordering and scalability, it's common to use a partition key that ensures related messages go to the same partition.


51. What is the role of the Kafka broker's log cleaner thread?

The log cleaner thread in Kafka is responsible for performing log compaction. Log compaction is a mechanism where Kafka removes redundant records from a log, keeping only the latest value for each key. This is useful for use cases where only the latest update for a given key is needed, such as maintaining a changelog or a database state. The log cleaner runs periodically to compact eligible topics.


52. How does Kafka handle consumer lag?

Consumer lag in Kafka refers to the difference between the offset of the last produced message and the offset of the last consumed message. Kafka provides tools and APIs to monitor consumer lag, such as the Kafka Consumer Groups command-line tool and the AdminClient API. High consumer lag can indicate performance issues or insufficient consumer capacity. Kafka doesn't automatically handle lag, but it provides the information needed for applications to make scaling or performance optimization decisions.


53. What is the purpose of the Kafka producer's Partitioner interface?

The Partitioner interface in Kafka's producer API determines which partition in the topic a message will be sent to. The default partitioner uses a hash of the key (if present) to choose the partition, ensuring that messages with the same key always go to the same partition. Custom partitioners can be implemented to control message distribution across partitions based on specific business logic or data characteristics.


54. How does Kafka handle message delivery timeouts?

Kafka producers can be configured with delivery timeouts. If a message cannot be successfully acknowledged within this timeout period, the producer will consider the send failed and may retry (depending on configuration). On the consumer side, there's a max.poll.interval.ms setting that controls how long a consumer can go without polling before it's considered failed and a rebalance is triggered.


55. What is the purpose of the Kafka Streams DSL?

The Kafka Streams DSL (Domain Specific Language) provides a high-level API for stream processing operations. It allows developers to express complex processing logic like filtering, transforming, aggregating, and joining streams of data. The DSL abstracts away many of the low-level details of stream processing, making it easier to build and maintain stream processing applications.


56. How does Kafka handle message de-duplication?

Kafka itself doesn't provide built-in de-duplication of messages. However, it provides mechanisms that allow applications to implement de-duplication:


Idempotent producers prevent duplicate messages due to producer retries.

Exactly-once semantics in Kafka Streams ensure that each input record is processed once.

For custom applications, unique message IDs can be used to detect and handle duplicates at the consumer level.

57. What is the role of the Kafka consumer's position() method?

The position() method in a Kafka consumer returns the offset of the next record that will be fetched for a given partition. This is useful for tracking the progress of consumption and can be used in conjunction with the committed() method to determine how far behind the consumer is from its last committed position. This information can be valuable for monitoring and managing consumer performance.


58. How does Kafka handle message schema evolution?

Kafka itself is agnostic to message schemas, treating messages as byte arrays. However, schema evolution is typically handled using a schema registry (like Confluent Schema Registry) in conjunction with a serialization format that supports schema evolution (like Avro). The schema registry maintains versions of schemas and ensures compatibility between producer and consumer schemas. This allows for schema changes over time while maintaining backward and forward compatibility.


59. What is the purpose of the Kafka broker's controlled shutdown?

Controlled shutdown is a feature in Kafka that allows a broker to shut down gracefully. During a controlled shutdown:


The broker stops accepting new produce requests

It completes all ongoing produce and fetch requests

It transfers leadership of its partitions to other brokers in a controlled manner This process minimizes data loss and service disruption when a broker needs to be taken offline for maintenance or other reasons.

60. How does Kafka handle message validation?

Kafka itself doesn't perform message validation beyond ensuring that messages don't exceed the configured maximum size. Message validation is typically handled at the producer or consumer level. Producers can implement validation logic before sending messages, while consumers can validate messages after receiving them. For more complex validation scenarios, intermediate processing steps (like Kafka Streams applications) can be used to validate and potentially transform messages.


61. What is the role of the Kafka consumer's commitSync() and commitAsync() methods?

These methods are used to commit offsets in Kafka consumers:


commitSync(): Synchronously commits the latest offset returned by poll(). It will retry until it succeeds or encounters a non-retriable error.

commitAsync(): Asynchronously commits offsets. It doesn't retry on failures, making it faster but less reliable than commitSync(). The choice between these methods depends on the balance between performance and reliability required by the application.

62. How does Kafka handle message retention across multiple data centers?

Kafka can handle message retention across multiple data centers through a feature called MirrorMaker. MirrorMaker is a stand-alone tool for copying data between Kafka clusters. It consumes from one cluster and produces to another, allowing for replication of data across different data centers. This can be used for disaster recovery, geographic distribution of data, or aggregating data from multiple sources into a central location.


63. What is the purpose of the Kafka producer's max.block.ms parameter?

The max.block.ms parameter in a Kafka producer controls how long the producer will block when calling send() and when explicitly requesting metadata via metadata(). If this time elapses before the producer can send the record, it will throw a TimeoutException. This parameter is useful for setting an upper bound on how long the application will wait in these scenarios, preventing indefinite blocking.


64. How does Kafka handle message consumption across consumer group rebalances?

When a consumer group rebalance occurs (due to consumers joining or leaving the group), Kafka ensures that:


All consumers stop consuming and commit their current offsets

The group coordinator reassigns partitions to the remaining consumers

Consumers start consuming from their newly assigned partitions, beginning from the last committed offset This process ensures that all messages are consumed exactly once (assuming proper offset management) even as the set of consumers changes.

65. What is the role of the Kafka broker's log.segment.bytes configuration?

The log.segment.bytes configuration in Kafka brokers controls the maximum size of a single log segment file. When a log segment reaches this size, a new segment is created. This configuration affects:


How often segments are closed and become eligible for deletion

The granularity of log retention (Kafka can only delete entire segments)

The amount of data that needs to be moved during partition reassignments Smaller segments allow for more granular retention and faster reassignments but can lead to more file handles and slightly higher overhead.

66. How does Kafka handle message consumption patterns?

Kafka supports two main consumption patterns:


Queue: Each message is processed by one consumer within a consumer group. This is achieved by having multiple consumers in a group, each reading from exclusive partitions.

Publish-Subscribe: All messages are processed by all consumers. This is achieved by having each consumer in its own consumer group, allowing all consumers to read all messages. These patterns can be combined and customized to fit various use cases.

67. What is the purpose of the Kafka producer's linger.ms parameter?

The linger.ms parameter in a Kafka producer controls the amount of time to wait for additional messages before sending a batch of messages. Increasing this value leads to larger batches and higher throughput at the cost of increased latency. Setting this to 0 (the default) means messages are sent as soon as possible. This parameter allows for fine-tuning the trade-off between latency and throughput in message production.


68. How does Kafka handle message delivery guarantees?

Kafka provides different levels of delivery guarantees:


At most once: Messages may be lost but are never redelivered.

At least once: Messages are never lost but may be redelivered.

Exactly once: Each message is delivered once and only once. These guarantees are achieved through a combination of producer acknowledgments, consumer offset management, and (for exactly once semantics) the transactions API. The choice depends on the specific requirements of the use case.

69. What is the role of the Kafka consumer's auto.offset.reset configuration?

The auto.offset.reset configuration in Kafka consumers determines what to do when there is no initial offset in Kafka or if the current offset no longer exists on the server. It can be set to:

earliest: automatically reset the offset to the earliest offset

latest: automatically reset the offset to the latest offset

none: throw exception to the consumer if no previous offset is found This configuration is crucial for defining behavior when a consumer starts reading from a topic for the first time or when it has been offline for a long time.

70. How does Kafka handle message retrieval for consumers?

Kafka uses a pull model for message retrieval. Consumers request messages from brokers rather than brokers pushing messages to consumers. This allows consumers to control the rate at which they receive messages. Consumers make fetch requests to brokers, specifying the topics, partitions, and starting offset for each partition. The broker responds with messages up to a specified maximum byte limit. This model allows for better flow control and makes it easier to handle scenarios where consumers fall behind. 

Java Stream API interview coding questions

 Java Stream API interview coding questions and uncover the secrets to mastering this powerful API!

  1. Write a program to find the sum of all elements in a list using Java Stream API
import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum);
}
}

Output:
Sum: 15

2. Given a list of integers, write a program to find and print the maximum element using Java Stream API

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(2, 4, 8, 6, 10);
int max = numbers.stream()
.mapToInt(Integer::intValue)
.max()
.orElseThrow();
System.out.println("Max element: " + max);
}
}

Output:
Max element: 10

3. Write a program to filter out all the even numbers from a list using Java Stream API

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(num -> num % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even numbers: " + evenNumbers);
}
}

Output:
Even numbers: [2, 4]

4. Given a list of strings, write a program to count the number of strings containing a specific character ‘a’ using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "orange", "grape");
char searchChar = 'a';
long count = strings.stream()
.filter(str -> str.contains(String.valueOf(searchChar)))
.count();
System.out.println("Number of strings containing '" + searchChar + "': " + count);
}
}

Output:
Number of strings containing 'a': 4

5. Write a program to convert a list of strings to uppercase using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "orange", "grape");
List<String> upperCaseStrings = strings.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("Uppercase strings: " + upperCaseStrings);
}
}

Output:
Uppercase strings: [APPLE, BANANA, ORANGE, GRAPE]

6. Given a list of integers, write a program to calculate the average of all the numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
OptionalDouble average = numbers.stream()
.mapToDouble(Integer::doubleValue)
.average();
System.out.println("Average: " + (average.isPresent() ? average.getAsDouble() : "N/A"));
}
}

Output:
Average: 3.0

7. Write a program to sort a list of strings in alphabetical order using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("banana", "orange", "apple", "grape");
List<String> sortedStrings = strings.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted strings: " + sortedStrings);
}
}

Output:
Sorted strings: [apple, banana, grape, orange]

8. Given a list of strings, write a program to concatenate all the strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "orange", "grape");
String concatenatedString = strings.stream()
.collect(Collectors.joining());
System.out.println("Concatenated string: " + concatenatedString);
}
}

Output:
Concatenated string: applebananaorangegrape

9. Write a program to find the longest string in a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "orange", "grape");
Optional<String> longestString = strings.stream()
.max((str1, str2) -> str1.length() - str2.length());
System.out.println("Longest string: " + (longestString.isPresent() ? longestString.get() : "N/A"));
}
}

Output:
Longest string: banana

10. Given a list of integers, write a program to find and print the second largest number using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(4, 2, 8, 6, 10);
Optional<Integer> secondLargest = numbers.stream()
.sorted((num1, num2) -> num2 - num1)
.skip(1)
.findFirst();
System.out.println("Second largest number: " + (secondLargest.isPresent() ? secondLargest.get() : "N/A"));
}
}

Output:
Second largest number: 8

11. Write a program to remove all the duplicate elements from a list using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 1);
List<Integer> uniqueNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("Original list: " + numbers);
System.out.println("List with duplicates removed: " + uniqueNumbers);
}
}

Output:
Original list: [1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 1]
List with duplicates removed: [1, 2, 3, 4, 5, 6, 7, 8]

12. Given a list of strings, write a program to find and print the shortest string using Java Stream API.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String shortestString = strings.stream()
.min(Comparator.comparingInt(String::length))
.orElse(null);
System.out.println("Shortest string: " + shortestString);
}
}

Output:
Shortest string: kiwi

13. Write a program to convert a list of integers to a list of their squares using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println("Original list: " + numbers);
System.out.println("List of squares: " + squares);
}
}

Output:
Original list: [1, 2, 3, 4, 5]
List of squares: [1, 4, 9, 16, 25]

14. Given a list of strings, write a program to find and print the strings starting with a specific prefix ‘a’ using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String prefix = "a";
List<String> stringsWithPrefix = strings.stream()
.filter(s -> s.startsWith(prefix))
.collect(Collectors.toList());
System.out.println("Strings starting with prefix '" + prefix + "': " + stringsWithPrefix);
}
}

Output:
Strings starting with prefix 'a': [apple]

15. Write a program to find the product of all elements in a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int product = numbers.stream()
.reduce(1, (a, b) -> a * b);
System.out.println("Product of all elements: " + product);
}
}

Output:
Product of all elements: 120

16. Given a list of integers, write a program to find and print the prime numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
List<Integer> primes = numbers.stream()
.filter(Main::isPrime)
.collect(Collectors.toList());
System.out.println("Prime numbers: " + primes);
}

private static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}

Output:
Prime numbers: [2, 3, 5, 7, 11]

17. Write a program to check if a list of strings contains a specific string using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String target = "banana";
boolean containsString = strings.stream()
.anyMatch(s -> s.equals(target));
System.out.println("List contains string '" + target + "': " + containsString);
}
}

Output:
List contains string 'banana': true

18. Given a list of strings, write a program to find and print the strings with length greater than a specified value 5 using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
int minLength = 5;
List<String> longStrings = strings.stream()
.filter(s -> s.length() > minLength)
.collect(Collectors.toList());
System.out.println("Strings with length greater than " + minLength + ": " + longStrings);
}
}

Output:
Strings with length greater than 5: [banana, orange]

19. Write a program to filter out all the elements divisible by 3 and 5 from a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
List<Integer> divisibleBy3And5 = numbers.stream()
.filter(n -> n % 3 == 0 && n % 5 == 0)
.collect(Collectors.toList());
System.out.println("Numbers divisible by 3 and 5: " + divisibleBy3And5);
}
}

Output:
Numbers divisible by 3 and 5: [15]

20. Given a list of strings, write a program to find and print the strings with the maximum length using Java Stream API.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Optional<String> maxLengthString = strings.stream()
.max(Comparator.comparingInt(String::length));
maxLengthString.ifPresent(s -> System.out.println("String with maximum length: " + s));
}
}

Output:
String with maximum length: banana

21. Write a program to reverse a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Collections.reverse(strings);
System.out.println("Reversed list: " + strings);
}
}

Output:
Reversed list: [pear, orange, kiwi, banana, apple]

22. Given a list of integers, write a program to find and print the distinct odd numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> distinctOddNumbers = numbers.stream()
.filter(n -> n % 2 != 0)
.distinct()
.collect(Collectors.toList());
System.out.println("Distinct odd numbers: " + distinctOddNumbers);
}
}

Output:
Distinct odd numbers: [1, 3, 5, 7, 9]

23. Write a program to remove all null values from a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", null, "banana", null, "kiwi", "orange", null, "pear");
List<String> nonNullStrings = strings.stream()
.filter(s -> s != null)
.collect(Collectors.toList());
System.out.println("List with null values removed: " + nonNullStrings);
}
}

Output:
List with null values removed: [apple, banana, kiwi, orange, pear]

24. Given a list of integers, write a program to find and print the sum of all odd numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int sumOfOddNumbers = numbers.stream()
.filter(n -> n % 2 != 0)
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum of odd numbers: " + sumOfOddNumbers);
}
}

Output:
Sum of odd numbers: 25

25. Write a program to find the intersection of two lists of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> list1 = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
List<String> list2 = Arrays.asList("banana", "orange", "grape", "watermelon");
List<String> intersection = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
System.out.println("Intersection of lists: " + intersection);
}
}

Output:
Intersection of lists: [banana, orange]

26. Given a list of strings, write a program to find and print the strings containing only vowels using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear", "oai");
List<String> vowelStrings = strings.stream()
.filter(s -> s.matches("[aeiouAEIOU]+"))
.collect(Collectors.toList());
System.out.println("Strings containing only vowels: " + vowelStrings);
}
}

Output:
Strings containing only vowels: [oai]

27. Write a program to convert a list of strings to a comma-separated string using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String commaSeparatedString = strings.stream()
.collect(Collectors.joining(", "));
System.out.println("Comma-separated string: " + commaSeparatedString);
}
}

Output:
Comma-separated string: apple, banana, kiwi, orange, pear

28. Given a list of integers, write a program to find and print the index of the first occurrence of a specific number using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 3, 5, 7, 9, 2, 4, 6, 8, 10);
int targetNumber = 7;
int index = numbers.indexOf(targetNumber);
System.out.println("Index of " + targetNumber + ": " + index);
}
}

Output:
Index of 7: 3

29. Write a program to find the union of two lists of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(4, 5, 6, 7, 8);
List<Integer> union = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
System.out.println("Union of lists: " + union);
}
}

Output:
Union of lists: [1, 2, 3, 4, 5, 6, 7, 8]

30. Given a list of strings, write a program to find and print the strings containing duplicate characters using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear", "strawberry", "watermelon");
List<String> duplicateStrings = strings.stream()
.filter(s -> s.length() != s.chars().distinct().count())
.collect(Collectors.toList());
System.out.println("Strings containing duplicate characters: " + duplicateStrings);
}
}

Output:
Strings containing duplicate characters: [apple, banana, kiwi, strawberry, watermelon]

31. Write a program to check if all elements in a list of strings are of the same length using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
boolean sameLength = strings.stream()
.map(String::length)
.distinct()
.count() == 1;
System.out.println("All elements have the same length: " + sameLength);
}
}

Output:
All elements have the same length: false

32. Given a list of integers, write a program to find and print the difference between the maximum and minimum numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 5, 7, 18, 3, 15);
OptionalInt max = numbers.stream().mapToInt(Integer::intValue).max();
OptionalInt min = numbers.stream().mapToInt(Integer::intValue).min();
int difference = max.getAsInt() - min.getAsInt();
System.out.println("Difference between maximum and minimum numbers: " + difference);
}
}

Output:
Difference between maximum and minimum numbers: 15

33. Write a program to remove all whitespace from a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "ba nana", "kiwi", "oran ge", "pear");
List<String> noWhitespace = strings.stream().map(s -> s.replaceAll("\\s", "")).collect(Collectors.toList());
System.out.println("List with whitespace removed: " + noWhitespace);
}
}

Output:
List with whitespace removed: [apple, banana, kiwi, orange, pear]

34. Given a list of strings, write a program to find and print the strings containing a specific substring using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String substring = "an";
List<String> containingSubstring = strings.stream().filter(s -> s.contains(substring)).collect(Collectors.toList());
System.out.println("Strings containing \"" + substring + "\": " + containingSubstring);
}
}

Output:
Strings containing "an": [banana, orange]

35. Write a program to find the mode of a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4, 4, 5, 5);
Map<Integer, Long> frequencyMap = numbers.stream().collect(Collectors.groupingBy(i -> i, Collectors.counting()));
long maxFrequency = frequencyMap.values().stream().mapToLong(Long::longValue).max().orElse(0);
List<Integer> modes = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == maxFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("Mode(s): " + modes);
}
}

Output:
Mode(s): [4]

36. Given a list of strings, write a program to find and print the strings with the minimum length using Java Stream API.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Optional<String> minLengthString = strings.stream().min(Comparator.comparingInt(String::length));
System.out.println("String with minimum length: " + minLengthString.orElse("No strings in the list"));
}
}

Output:
String with minimum length: kiwi

37. Write a program to find the frequency of each element in a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4, 4, 5, 5);
Map<Integer, Long> frequencyMap = numbers.stream().collect(Collectors.groupingBy(i -> i, Collectors.counting()));
System.out.println("Frequency of each element: " + frequencyMap);
}
}

Output:
Frequency of each element: {1=1, 2=1, 3=2, 4=3, 5=2}

38. Given a list of strings, write a program to find and print the strings with the maximum number of vowels using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Map<String, Long> frequencyMap = strings.stream()
.collect(Collectors.toMap(s -> s, s -> s.chars().filter(c -> "AEIOUaeiou".indexOf(c) != -1).count()));
long maxVowelCount = frequencyMap.values().stream().mapToLong(Long::longValue).max().orElse(0);
List<String> maxVowelStrings = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == maxVowelCount)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("String(s) with maximum number of vowels: " + maxVowelStrings);
}
}

Output:
String(s) with maximum number of vowels: [banana, orange]

39. Write a program to check if a list of integers is sorted in ascending order using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 5, 4);
boolean sortedAscending = numbers.stream().sorted().collect(Collectors.toList()).equals(numbers);
System.out.println("Is the list sorted in ascending order? " + sortedAscending);
}
}

Output:
Is the list sorted in ascending order? false

40. Given a list of strings, write a program to find and print the strings with the minimum number of vowels using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Map<String, Long> frequencyMap = strings.stream()
.collect(Collectors.toMap(s -> s, s -> s.chars().filter(c -> "AEIOUaeiou".indexOf(c) != -1).count()));
long minVowelCount = frequencyMap.values().stream().mapToLong(Long::longValue).min().orElse(0);
List<String> minVowelStrings = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == minVowelCount)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("String(s) with minimum number of vowels: " + minVowelStrings);
}
}

Output:
String(s) with minimum number of vowels: [apple, kiwi, pear]

41. Write a program to find the median of a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
OptionalDouble median = numbers.stream().mapToInt(Integer::intValue).sorted()
.skip((numbers.size() - 1) / 2)
.limit(numbers.size() % 2 == 0 ? 2 : 1)
.average();
System.out.println("Median of the list: " + (median.isPresent() ? median.getAsDouble() : "N/A"));
}
}

Output:
Median of the list: 3.0

42. Given a list of strings, write a program to find and print the strings containing a specific character at least twice using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
char targetChar = 'a';
List<String> containingCharTwice = strings.stream()
.filter(s -> s.chars().filter(c -> c == targetChar).count() >= 2)
.collect(Collectors.toList());
System.out.println("Strings containing \"" + targetChar + "\" at least twice: " + containingCharTwice);
}
}

Output:
Strings containing "a" at least twice: [banana]

43. Write a program to find the kth smallest element in a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5);
int k = 3; // Find the 3rd smallest element
Optional<Integer> kthSmallest = numbers.stream().sorted().skip(k - 1).findFirst();
System.out.println("The " + k + "th smallest element: " + (kthSmallest.isPresent() ? kthSmallest.get() : "N/A"));
}
}

Output:
The 3th smallest element: 2

44. Given a list of strings, write a program to find and print the strings with the maximum number of consonants using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Map<String, Long> frequencyMap = strings.stream()
.collect(Collectors.toMap(s -> s, s -> s.chars().filter(c -> "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz".indexOf(c) != -1).count()));
long maxConsonantCount = frequencyMap.values().stream().mapToLong(Long::longValue).max().orElse(0);
List<String> maxConsonantStrings = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == maxConsonantCount)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("String(s) with maximum number of consonants: " + maxConsonantStrings);
}
}

Output:
String(s) with maximum number of consonants: [banana, orange, apple]

45. Write a program to check if a list of strings is palindrome using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "banana", "apple");
boolean isPalindrome = strings.stream()
.skip(strings.size() / 2)
.allMatch(s -> s.equals(strings.get(strings.size() - 1 - strings.indexOf(s))));
System.out.println("Is the list a palindrome? " + isPalindrome);
}
}

Output:
Is the list a palindrome? true

46. Given a list of integers, write a program to find and print the elements with the highest frequency using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4, 4, 5, 5);
Map<Integer, Long> frequencyMap = numbers.stream().collect(Collectors.groupingBy(i -> i, Collectors.counting()));
long maxFrequency = frequencyMap.values().stream().mapToLong(Long::longValue).max().orElse(0);
List<Integer> elementsWithMaxFrequency = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == maxFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("Element(s) with highest frequency: " + elementsWithMaxFrequency);
}
}

Output:
Element(s) with highest frequency: [4]

47. Write a program to remove all non-numeric characters from a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("a1b2c3", "1a2b3c", "123abc");
Pattern pattern = Pattern.compile("[^0-9]");
List<String> numericStrings = strings.stream()
.map(s -> pattern.matcher(s).replaceAll(""))
.collect(Collectors.toList());
System.out.println("List with non-numeric characters removed: " + numericStrings);
}
}

Output:
List with non-numeric characters removed: [123, 123, 123]

48. Given a list of strings, write a program to find and print the strings containing only digits using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("123", "abc", "456", "789", "def");
Predicate<String> containsOnlyDigits = s -> s.matches("\\d+");
List<String> digitStrings = strings.stream().filter(containsOnlyDigits).collect(Collectors.toList());
System.out.println("Strings containing only digits: " + digitStrings);
}
}

Output:
Strings containing only digits: [123, 456, 789]

49. Write a program to find the kth largest element in a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5);
int k = 3; // Find the 3rd largest element
Collections.sort(numbers, Collections.reverseOrder());
Integer kthLargest = numbers.stream().distinct().skip(k - 1).findFirst().orElse(null);
System.out.println("The " + k + "th largest element: " + kthLargest);
}
}

Output:
The 3th largest element: 5

50. Given a list of integers, write a program to find and print the elements with the lowest frequency using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4, 4, 5, 5);
Map<Integer, Long> frequencyMap = numbers.stream().collect(Collectors.groupingBy(i -> i, Collectors.counting()));
long minFrequency = frequencyMap.values().stream().mapToLong(Long::longValue).min().orElse(0);
List<Integer> elementsWithMinFrequency = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == minFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("Element(s) with lowest frequency: " + elementsWithMinFrequency);
}
}

Output:
Element(s) with lowest frequency: [1, 2]

Thank you for taking the time to read this article.