0% found this document useful (0 votes)
9 views24 pages

Java8_CodingProgramms

The document provides a collection of Java 8 coding questions and answers, focusing on various functionalities such as finding duplicates, counting occurrences, swapping values, and using streams for operations on lists and arrays. It includes code snippets for each problem along with their outputs. Key topics covered include finding maximum and minimum values, sorting, and filtering elements in lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views24 pages

Java8_CodingProgramms

The document provides a collection of Java 8 coding questions and answers, focusing on various functionalities such as finding duplicates, counting occurrences, swapping values, and using streams for operations on lists and arrays. It includes code snippets for each problem along with their outputs. Key topics covered include finding maximum and minimum values, sorting, and filtering elements in lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

JAVA8 CODING QUESTIONS AND ANSWERS

1 How to find duplicate elements in a given integers list in java using


Stream functions?

public class DuplicatElements {

public static void main(String args[]) {


List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
Set<Integer> set = new HashSet();
myList.stream()
.filter(n -> !set.add(n))
.forEach(System.out::println);
}

Output:
98, 15

2 Count the repeated occurance in string in java8

public class DuplicatElements {

public static void main(String args[]) {


String inputString = "manoharsingh";

Map<Character, Long> charCountMap = inputString.chars()


.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));

System.out.println("Character occurrences in the string:");


charCountMap.forEach((character, count) ->
System.out.println(character + ": " + count));
}
}

O/P
Character occurrences in the string:
a: 2
r: 1
s: 1
g: 1
h: 2
i: 1
m: 1
n: 2
o: 1

3 How to find duplicate names in a given list in java


using Stream functions?
public class DuplicatElements {

public static void main(String args[]) {


List<String> names = Arrays.asList("John", "Alice", "Bob",
"John", "Charlie", "Alice", "David");

Map<String, Long> nameCountMap = names.stream()


.collect(Collectors.groupingBy(Function.i
dentity(), Collectors.counting()));

System.out.println("Duplicate names in the list:");


nameCountMap.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.forEach(entry ->
System.out.println(entry.getKey() + ": " + entry.getValue()));
}
}

O/P
Duplicate names in the list:
Alice: 2
John: 2

4 Java Program to Swap Two Strings Without Using


Third Variable

Public class DuplicatElements {

public static void main(String args[]) {


String str1 = "Hello";
String str2 = "World";

System.out.println("Before swapping: ");


System.out.println("str1: " + str1);
System.out.println("str2: " + str2);

str1 = str1 + str2;


str2 = str1.substring(0, str1.length() - str2.length());
str1 = str1.substring(str2.length());

System.out.println("\nAfter swapping: ");


System.out.println("str1: " + str1);
System.out.println("str2: " + str2);
}
}
O/P
Before swapping:
str1: Hello
str2: World

After swapping:
str1: World
str2: Hello
5 Java Program to Swap Two numbers Without Using Third
Variable

public class DuplicatElements {

public static void main(String args[]) {


int num1 = 5;
int num2 = 10;

System.out.println("Before swapping:");
System.out.println("num1: " + num1);
System.out.println("num2: " + num2);

// Swapping without using a third variable


num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;

System.out.println("\nAfter swapping:");
System.out.println("num1: " + num1);
System.out.println("num2: " + num2);
}
}

O/P
Before swapping:
num1: 5
num2: 10

After swapping:
num1: 10
num2: 5

6 Given the list of integers, find the first element of the list using
Stream functions?

public class DuplicatElements {

public static void main(String args[]) {


List<Integer> myList =
Arrays.asList(10,15,8,49,25,98,98,32,15);
myList.stream()
.findFirst()
.ifPresent(System.out::println);
}
}
O/P
10
7 Given a list of integers, find the total number of elements present
in the list using Stream functions?

public class JavaHungry {


public static void main(String args[]) {
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
long count = myList.stream()
.count();
System.out.println(count);
}
}

Output:
9

8 Given a list of integers, find the maximum value element present in


it using Stream functions?

public class JavaHungry {


public static void main(String args[]) {
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
int max = myList.stream()
.max(Integer::compare)
.get();
System.out.println(max);
}
}

Output:
98

9 Given a String, find the first non-repeated character in it using


Stream functions?

public class DuplicatElements {

public static void main(String args[]) {


String input = "manoharsingh";

Character result = input.chars() // Stream of String


.mapToObj(s ->
Character.toLowerCase(Character.valueOf((char) s))) // First convert to
Character object and then to lowercase
.collect(Collectors.groupingBy(Function.id
entity(), LinkedHashMap::new, Collectors.counting())) //Store the chars in
map with count
.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1L)
.map(entry -> entry.getKey())
.findFirst()
.get();
System.out.println(result);
}
}
O/P
m
10 Given a String, find the first repeated character in it using Stream
functions?

public class DuplicatElements {

public static void main(String args[]) {


String input = "manoharsingh";

Character result = input.chars() // Stream of String


.mapToObj(s ->
Character.toLowerCase(Character.valueOf((char) s))) // First convert to
Character object and then to lowercase
.collect(Collectors.groupingBy(Function.i
dentity(), LinkedHashMap::new, Collectors.counting())) //Store the chars in
map with count
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1L)
.map(entry -> entry.getKey())
.findFirst()
.get();
System.out.println(result);
}
}

O/P
a

11 Given a list of integers, sort all the values present in it in


descending order using Stream functions?

public class DuplicatElements {

public static void main(String args[]) {


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

myList.stream()
.sorted(Collections.reverseOrder())
.forEach(System.out::println);
}
}
Output:
98
98
49
32
25
15
15
10
8

12 Given a list of integers, sort all the values present in it using


Stream functions?

public class JavaHungry {


public static void main(String args[]) {
List<Integer> myList =
Arrays.asList(10,15,8,49,25,98,98,32,15);

myList.stream()
.sorted()
.forEach(System.out::println);
}
}
Output:
8
10
15
15
25
32
49
98
98

13 How do you remove duplicate elements from a list using Java 8


streams?
public class DuplicatElements {

public static void main(String args[]) {


List<String> listOfStrings = Arrays.asList("Java", "Python",
"C#", "Java", "Kotlin", "Python");

List<String> uniqueStrngs =
listOfStrings.stream().distinct().collect(Collectors.toList());

System.out.println(uniqueStrngs);
}
}
O/P

[Java, Python, C#, Kotlin]

14 Given a list of integers, find maximum and minimum of those


numbers?

public class DuplicatElements {

public static void main(String args[]) {

List<Integer> listOfIntegers = Arrays.asList(45, 12, 56, 15,


24, 75, 31, 89);

int max =
listOfIntegers.stream().max(Comparator.naturalOrder()).get();

System.out.println("Maximum Element : "+max);

int min =
listOfIntegers.stream().min(Comparator.naturalOrder()).get();

System.out.println("Minimum Element : "+min);


}
}

Output :

Maximum Element : 89
Minimum Element : 12

15 Find second largest number in an integer array?


public class DuplicatElements {

public static void main(String args[]) {

List<Integer> listOfIntegers = Arrays.asList(45, 12, 56, 15,


24, 75, 31, 89);

Integer secondLargestNumber =
listOfIntegers.stream().sorted(Comparator.reverseOrder()).skip(1).findFirst
().get();

System.out.println(secondLargestNumber);
}
}

O/P
75

16 Find 3rd largest number in an integer array?


public class DuplicatElements {

public static void main(String args[]) {

List<Integer> listOfIntegers = Arrays.asList(45, 12, 56, 15,


24, 75, 31, 89);

// Integer secondLargestNumber =
listOfIntegers.stream().sorted(Comparator.reverseOrder()).skip(1).findFirst
().get();

Integer thirdLargestNumber =
listOfIntegers.stream().sorted(Comparator.reverseOrder()).skip(2).findFirst
().get();
System.out.println(thirdLargestNumber);
}
}

O/P
56
17 Find maximum element of ArrayList with Java

public class DuplicatElements {

public static void main(String args[]) {


List<Integer> list = new ArrayList<Integer>();
try {
list.add(14);
list.add(2);
list.add(73);
System.out.println("Maximum element : " +
Collections.max(list));
}
catch (ClassCastException | NoSuchElementException e) {
System.out.println("Exception caught : " + e);
}
}
O/P Maximum element : 73
18 How will you get the current date and time using
Java 8 Date and Time API?
public class DuplicatElements {

public static void main(String args[]) {


System.out.println("Current Local Date: " +
java.time.LocalDate.now());
//Used LocalDate API to get the date
System.out.println("Current Local Time: " +
java.time.LocalTime.now());
//Used LocalTime API to get the time
System.out.println("Current Local Date and Time: " +
java.time.LocalDateTime.now());
//Used LocalDateTime API to get both date and time
}
}

O/P
Current Local Date: 2023-12-24
Current Local Time: 00:03:31.476149400
Current Local Date and Time: 2023-12-24T00:03:31.476149400

19 How do you get last element of an arrayList?


public class DuplicatElements {

public static void main(String args[]) {


/*
List<Integer> listOfStrings = Arrays.asList(1,2,3,4,5,6);

Integer lastElement =
listOfStrings.stream().skip(listOfStrings.size()-1 ).findFirst().get();

System.out.println(lastElement);
}
}

*/

List<String> listOfStrings = Arrays.asList("One",


"Two", "Three", "Four", "Five", "Six");

String lastElement =
listOfStrings.stream().skip(listOfStrings.size() - 1).findFirst().get();

System.out.println(lastElement);
}
}
O/P
Six

20 How do you get middle element of an array list in


java
OR
How do you get second element of an array list in java
How do you get First element of an array list in java
How do you get Last element of an array list in java

public class DuplicatElements {

public static void main(String args[]) {

List<Integer> arrayList = new ArrayList<>();


arrayList.add(10);
arrayList.add(5);
arrayList.add(7);
arrayList.add(2);
arrayList.add(8);
/*
How do you get middle element of an array list *****

// System.out.println(arrayList.get(2)); -----> middle


element is o/p is 7

// Get the middle element


Integer middleElement = getMiddleElement(arrayList);

// Display the result


System.out.println("The middle element of the ArrayList is: "
+ middleElement);
}

// Function to get the middle element of an ArrayList


private static Integer getMiddleElement(List<Integer> list) {
if (list == null || list.isEmpty()) {
throw new IllegalArgumentException("ArrayList is empty or
null");
}

// Calculate the index of the middle element


int middleIndex = list.size() / 2;

// Get the middle element


return list.get(middleIndex); ---->o/p 7
--------------end---------------------------
*/
// How do you get second element of an array list *****

/* ------------------start---------------
Integer secondElement = getSecondElement(arrayList);

// Display the result


System.out.println("The second element of the ArrayList is: "
+ secondElement);
}

// Function to get the second element of an ArrayList


private static Integer getSecondElement(List<Integer> list) {
if (list == null || list.size() < 2) {
throw new IllegalArgumentException("ArrayList has fewer
than two elements");
}

// Get the second element using index 1


return list.get(1); ---->o/p 5

--------------end---------------------------

*/

/* ------------------start---------------
Integer lastElement = getLastElement(arrayList);

// Display the result


System.out.println("The last element of the ArrayList is: " +
lastElement);
}

// Function to get the last element of an ArrayList


private static Integer getLastElement(List<Integer> list) {
if (list == null || list.isEmpty()) {
throw new IllegalArgumentException("ArrayList is empty or
null");
}

// Get the last element using the size of the ArrayList


return list.get(list.size() - 1); ---->o/p 8

--------------end---------------------------
*/

Integer firstElement = getFirstElement(arrayList);

// Display the result


System.out.println("The first element of the ArrayList is: "
+ firstElement);
}

// Function to get the first element of an ArrayList


private static Integer getFirstElement(List<Integer> list) {
if (list == null || list.isEmpty()) {
throw new IllegalArgumentException("ArrayList is empty or
null");
}

// Get the first element using index 0


return list.get(0); // o/p --->10

21 Find out two arrays common elements in java8


public class DuplicatElements {

public static void main(String args[]) {


Integer[] array1 = {1, 2, 3, 4, 5};
Integer[] array2 = {4, 5, 6, 7, 8};

List<Integer> commonElements = findCommonElements(array1,


array2);

System.out.println("Common elements: " + commonElements);


}

public static <T> List<T> findCommonElements(T[] array1, T[]


array2) {
return Arrays.stream(array1)
.filter(Arrays.asList(array2)::contains)
.collect(Collectors.toList());
}
}

O/P
Common elements: [4, 5]

22 find the name which is start with A in java8

public class DuplicatElements {

public static void main(String args[]) {

List<String>list=Arrays.asList("sing","manohar","aruna","anil");

list=list.stream().filter(e>e.startsWith("a")).collect(Collectors.toList())
;

for(String list1:list) {
System.out.println(list1);

}
}
}
O/P
aruna
anil

23 write a program to print the maximum salary of an


employee from each department from java8

public class EmployeeFilter {


public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Alice", "HR", 50000),
new Employee("Bob", "IT", 60000),
new Employee("Bob", "IT", 5000),
new Employee("Charlie", "HR", 55000),
new Employee("David", "IT", 70000),
new Employee("David", "IT", 72000),
new Employee("Eva", "Finance", 75000),
new Employee("Eva", "Finance", 70000)
);

Map<String, Double> maxSalaryByDepartment =


findMaxSalaryByDepartment(employees);

maxSalaryByDepartment.forEach((department,
maxSalary) -> System.out.println("Max salary in department " + department
+ ": " + maxSalary));
}

public static Map<String, Double>


findMaxSalaryByDepartment(List<Employee> employees) {
return employees.stream()
.collect(Collectors.groupingBy(Employee::
getDepartment,

Collectors.mapping(Employee::getSalary,
Collectors.maxBy(Double::compare))))
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry ->
entry.getValue().orElseThrow(() -> new IllegalStateException("No max
value"))
));
}
}

O/P
Max salary in department Finance: 75000.0
Max salary in department HR: 55000.0
Max salary in department IT: 72000.0

24 Sort employees based on department name in


descending order

public class EmployeeFilter {

public static void main(String[] args) {


List<Employee> employees = Arrays.asList(
new Employee("Alice", "HR",5000),
new Employee("Bob", "IT",6000),
new Employee("Charlie", "HR",7000),
new Employee("David", "IT",8000),
new Employee("Eva", "Finance",9000)
);

// Sort employees based on department name in


descending order
List<Employee> sortedEmployees =
sortEmployeesByDepartmentDescending(employees);

// Print sorted employees


sortedEmployees.forEach(System.out::println);
}

public static List<Employee>


sortEmployeesByDepartmentDescending(List<Employee> employees) {
return employees.stream()
.sorted(Comparator.comparing(Employee::getDepar
tment).reversed())
.collect(Collectors.toList());
}
}

O/P
Employee{name='Bob', department='IT', salary=6000.0}
Employee{name='David', department='IT', salary=8000.0}
Employee{name='Alice', department='HR', salary=5000.0}
Employee{name='Charlie', department='HR', salary=7000.0}
Employee{name='Eva', department='Finance', salary=9000.0}

25 How do you sort the given list of integers in reverse order?


public class EmployeeFilter {

public static void main(String[] args) {

List<Integer> decimalList =
Arrays.asList(1,2,3,4,4,5,6,7,8);

decimalList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::
print);
}
}
O/P
8
7
6
5
4
4
3
2
1

26 What does the filter() method do? when you use it?
The filter method is used to filter elements that satisfy a certain condition
that is specified using a Predicate function.

A predicate function is nothing but a function that takes an Object and


returns a boolean. For example, if you have a List of Integer and you want
a list of even integers.
In this case, you can use the filter to achieve that. You supply a function to
check if a number is even or odd, just like this function, and filter will apply
this to stream elements and filter the elements which satisfy the condition
and which don't.

27 Print the name of all departments in the organization?

Use distinct() method after calling map(Employee::getDepartment) on the


stream. It will return unique departments.

Ex:

employeeList.stream()
.map(Employee::getDepartment)
.distinct()
.forEach(System.out::println);

O/P
HR
Sales And Marketing
Infrastructure
Product Development
Security And Transport
Account And Finance

28 How many male and female employees are there in the organization

Map<String, Long> noOfMaleAndFemaleEmployees=

employeeList.stream().collect(Collectors.groupingBy(Employee::getGender,
Collectors.counting()));

System.out.println(noOfMaleAndFemaleEmployees);

O/P
{Male=11, Female=6}

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

Map<String, Double> avgAgeOfMaleAndFemaleEmployees=

employeeList.stream().collect(Collectors.groupingBy(Employee::getGender,
Collectors.averagingInt(Employee::getAge)));

System.out.println(avgAgeOfMaleAndFemaleEmployees);

O/P
{Male=30.181818181818183, Female=27.166666666666668}

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

Optional<Employee> highestPaidEmployeeWrapper=

employeeList.stream().collect(Collectors.maxBy(Comparator.comparingDouble(E
mployee::getSalary)));

Employee highestPaidEmployee = highestPaidEmployeeWrapper.get();

System.out.println("Details Of Highest Paid Employee : ");

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

System.out.println("ID :
"+highestPaidEmployee.getId());

System.out.println("Name :
"+highestPaidEmployee.getName());

System.out.println("Age :
"+highestPaidEmployee.getAge());

System.out.println("Gender :
"+highestPaidEmployee.getGender());

System.out.println("Department :
"+highestPaidEmployee.getDepartment());

System.out.println("Year Of Joining :
"+highestPaidEmployee.getYearOfJoining());

System.out.println("Salary :
"+highestPaidEmployee.getSalary());

Output :

Details Of Highest Paid Employee :


==================================
ID : 277
Name : Anuj Chettiar
Age : 31
Gender : Male
Department : Product Development
Year Of Joining : 2012
Salary : 35700.0

31 Get the names of all employees who have joined after 2015?

employeeList.stream()
.filter(e -> e.getYearOfJoining() > 2015)
.map(Employee::getName)
.forEach(System.out::println);

Output :

Iqbal Hussain
Amelia Zoe
Nitin Joshi
Nicolus Den
Ali Baig

32 Count the number of employees in department in


java8

Map<String, Long> employeeCountByDepartment =


countEmployeesByDepartment(employeeList);

// Print the result


employeeCountByDepartment.forEach((department, count) ->
System.out.println("Number of employees in " + department + ": " +
count));
}

public static Map<String, Long>


countEmployeesByDepartment(List<Employee> employees) {
return employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.counting()));

O/P
--------------------
Number of employees in Product Development: 5
Number of employees in Security And Transport: 2
Number of employees in Sales And Marketing: 3
Number of employees in Infrastructure: 3
Number of employees in HR: 2
Number of employees in Account And Finance: 2
33 List down the names of all employees in each department?

Map<String, List<Employee>> employeeListByDepartment=

employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment
));

Set<Entry<String, List<Employee>>> entrySet =


employeeListByDepartment.entrySet();

for (Entry<String, List<Employee>> entry : entrySet) {


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

System.out.println("Employees In "+entry.getKey() + " : ");


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

List<Employee> list = entry.getValue();

for (Employee e : list) {


System.out.println(e.getName());
}
}

O/P
--------------------
--------------------------------------
Employees In Product Development :
--------------------------------------
Murali Gowda
Wang Liu
Nitin Joshi
Sanvi Pandey
Anuj Chettiar
--------------------------------------
Employees In Security And Transport :
--------------------------------------
Iqbal Hussain
Jaden Dough
--------------------------------------
Employees In Sales And Marketing :
--------------------------------------
Paul Niksui
Amelia Zoe
Nicolus Den
--------------------------------------
Employees In Infrastructure :
--------------------------------------
Martin Theron
Jasna Kaur
Ali Baig
--------------------------------------
Employees In HR :
--------------------------------------
Jiya Brein
Nima Roy
--------------------------------------
Employees In Account And Finance :
--------------------------------------
Manu Sharma
Jyothi Reddy

34 We have the list of numbers, each number is multiple by 2 in java8

public class EvenNumbersInStream {

public static void main(String[] args) {

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

numbers.stream().map(x-> x*2).forEach(System.out::println);

}
}
O/P
2
4
6
8
10

35 Filter the number which is greater than 2 in java8

public class EvenNumbersInStream {

public static void main(String[] args) {


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

numbers.stream().filter(x-> x>2).forEach(System.out::println);

}
}

O/P
3
4
5

36 Sort the list in ascending order in java8


public class EvenNumbersInStream {

public static void main(String[] args) {


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

List<Integer>
list1=numbers.stream().sorted().collect(Collectors.toList());

System.out.println(list1);

O/P
[1, 2, 3, 4, 5]

37 Sort the list in descending order in java8

public class EvenNumbersInStream {

public static void main(String[] args) {


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

numbers.stream().sorted(Comparator.reverseOrder()).forEach(System.out::prin
tln);

//System.out.println(list1);

}
}
O/P
5
4
3
2
1

38 Count the number of list in java8

public class EvenNumbersInStream {

public static void main(String[] args) {


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

long number=numbers.stream().count();

System.out.println(number);
}
}

O/P
5

39 Find the each department name in employee list in java8

employeeList.stream().map(Employee::getDepartment).di
stinct().forEach(System.out::println);
40 Find the each employee count in all departments in java8

Map< String,Long>
map=employeeList.stream().collect(Collectors.groupingBy(Employee::getDepart
ment,Collectors.counting()));

System.out.println(map);

O/P
{Product Development=5, Security And Transport=2, Sales And Marketing=3,
Infrastructure=3, HR=2, Account And Finance=2}

41 Find the employee Name,City in Employee list in


java8
42 Fibonacci numbers in java8 example

ublic class EvenNumbersInStream {

public static void main(String[] args) {


int n = 10; // Change this value to generate the first n
Fibonacci numbers

System.out.println("First " + n + " Fibonacci numbers:");


fibonacciSequence(n).forEach(System.out::println);
}

public static Stream<Integer> fibonacciSequence(int n) {


return Stream.iterate(new int[]{0, 1}, fib -> new int[]{fib[1],
fib[0] + fib[1]})
.limit(n)
.map(fib -> fib[0]);
}
}

O/P

First 10 Fibonacci numbers:


0
1
1
2
3
5
8
13
21
34

42 What is the difference between groupBy and orderBy


and having clauses in sql ******

GROUP BY:
Usage: The GROUP BY clause is used to group rows that
have the same values in specified columns into
summary rows.
Function: It is often used in combination with
aggregate functions (such as COUNT, SUM, AVG, etc.)
to perform operations on each group of rows.

EX:
SELECT department, COUNT(*) as employee_count
FROM employees
GROUP BY department;

ORDER BY:
Usage: The ORDER BY clause is used to sort the result
set based on one or more columns.
Function: It sorts the result set either in ascending
(default) or descending order for each specified
column.

EX:

SELECT employee_name, salary


FROM employees
ORDER BY salary DESC;

HAVING:
Usage: The HAVING clause is used to filter the
results of a GROUP BY clause based on specified
conditions.
Function: It is similar to the WHERE clause but is
applied after the GROUP BY and aggregate functions,
allowing you to filter on aggregated values.

EX:

SELECT department, AVG(salary) as avg_salary


FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;

In summary:

GROUPBY is used for grouping rows based on certain


columns.
ORDER BY is used for sorting the result set.
HAVING is used for filtering the result set after
grouping, especially when dealing with aggregated
values.

You might also like