[Go to site: main page, start]

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

Java 8 Coding Questions & Solutions

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)
41 views24 pages

Java 8 Coding Questions & Solutions

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

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 = [Link](10,15,8,49,25,98,98,32,15);
Set<Integer> set = new HashSet();
[Link]()
.filter(n -> ![Link](n))
.forEach([Link]::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 = [Link]()


.mapToObj(c -> (char) c)
.collect([Link]([Link](),
[Link]()));

[Link]("Character occurrences in the string:");


[Link]((character, count) ->
[Link](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 = [Link]("John", "Alice", "Bob",
"John", "Charlie", "Alice", "David");

Map<String, Long> nameCountMap = [Link]()


.collect([Link](Function.i
dentity(), [Link]()));

[Link]("Duplicate names in the list:");


[Link]().stream()
.filter(entry -> [Link]() > 1)
.forEach(entry ->
[Link]([Link]() + ": " + [Link]()));
}
}

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";

[Link]("Before swapping: ");


[Link]("str1: " + str1);
[Link]("str2: " + str2);

str1 = str1 + str2;


str2 = [Link](0, [Link]() - [Link]());
str1 = [Link]([Link]());

[Link]("\nAfter swapping: ");


[Link]("str1: " + str1);
[Link]("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;

[Link]("Before swapping:");
[Link]("num1: " + num1);
[Link]("num2: " + num2);

// Swapping without using a third variable


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

[Link]("\nAfter swapping:");
[Link]("num1: " + num1);
[Link]("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 =
[Link](10,15,8,49,25,98,98,32,15);
[Link]()
.findFirst()
.ifPresent([Link]::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 = [Link](10,15,8,49,25,98,98,32,15);
long count = [Link]()
.count();
[Link](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 = [Link](10,15,8,49,25,98,98,32,15);
int max = [Link]()
.max(Integer::compare)
.get();
[Link](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 = [Link]() // Stream of String


.mapToObj(s ->
[Link]([Link]((char) s))) // First convert to
Character object and then to lowercase
.collect([Link]([Link]
entity(), LinkedHashMap::new, [Link]())) //Store the chars in
map with count
.entrySet()
.stream()
.filter(entry -> [Link]() == 1L)
.map(entry -> [Link]())
.findFirst()
.get();
[Link](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 = [Link]() // Stream of String


.mapToObj(s ->
[Link]([Link]((char) s))) // First convert to
Character object and then to lowercase
.collect([Link](Function.i
dentity(), LinkedHashMap::new, [Link]())) //Store the chars in
map with count
.entrySet()
.stream()
.filter(entry -> [Link]() > 1L)
.map(entry -> [Link]())
.findFirst()
.get();
[Link](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 =
[Link](10,15,8,49,25,98,98,32,15);

[Link]()
.sorted([Link]())
.forEach([Link]::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 =
[Link](10,15,8,49,25,98,98,32,15);

[Link]()
.sorted()
.forEach([Link]::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 = [Link]("Java", "Python",
"C#", "Java", "Kotlin", "Python");

List<String> uniqueStrngs =
[Link]().distinct().collect([Link]());

[Link](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 = [Link](45, 12, 56, 15,


24, 75, 31, 89);

int max =
[Link]().max([Link]()).get();

[Link]("Maximum Element : "+max);

int min =
[Link]().min([Link]()).get();

[Link]("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 = [Link](45, 12, 56, 15,


24, 75, 31, 89);

Integer secondLargestNumber =
[Link]().sorted([Link]()).skip(1).findFirst
().get();

[Link](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 = [Link](45, 12, 56, 15,


24, 75, 31, 89);

// Integer secondLargestNumber =
[Link]().sorted([Link]()).skip(1).findFirst
().get();

Integer thirdLargestNumber =
[Link]().sorted([Link]()).skip(2).findFirst
().get();
[Link](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 {
[Link](14);
[Link](2);
[Link](73);
[Link]("Maximum element : " +
[Link](list));
}
catch (ClassCastException | NoSuchElementException e) {
[Link]("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[]) {


[Link]("Current Local Date: " +
[Link]());
//Used LocalDate API to get the date
[Link]("Current Local Time: " +
[Link]());
//Used LocalTime API to get the time
[Link]("Current Local Date and Time: " +
[Link]());
//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 = [Link](1,2,3,4,5,6);

Integer lastElement =
[Link]().skip([Link]()-1 ).findFirst().get();

[Link](lastElement);
}
}

*/

List<String> listOfStrings = [Link]("One",


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

String lastElement =
[Link]().skip([Link]() - 1).findFirst().get();

[Link](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<>();


[Link](10);
[Link](5);
[Link](7);
[Link](2);
[Link](8);
/*
How do you get middle element of an array list *****

// [Link]([Link](2)); -----> middle


element is o/p is 7

// Get the middle element


Integer middleElement = getMiddleElement(arrayList);

// Display the result


[Link]("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 || [Link]()) {
throw new IllegalArgumentException("ArrayList is empty or
null");
}

// Calculate the index of the middle element


int middleIndex = [Link]() / 2;

// Get the middle element


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

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

// Display the result


[Link]("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 || [Link]() < 2) {
throw new IllegalArgumentException("ArrayList has fewer
than two elements");
}

// Get the second element using index 1


return [Link](1); ---->o/p 5

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

*/

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

// Display the result


[Link]("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 || [Link]()) {
throw new IllegalArgumentException("ArrayList is empty or
null");
}

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


return [Link]([Link]() - 1); ---->o/p 8

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

Integer firstElement = getFirstElement(arrayList);

// Display the result


[Link]("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 || [Link]()) {
throw new IllegalArgumentException("ArrayList is empty or
null");
}

// Get the first element using index 0


return [Link](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);

[Link]("Common elements: " + commonElements);


}

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


array2) {
return [Link](array1)
.filter([Link](array2)::contains)
.collect([Link]());
}
}

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=[Link]("sing","manohar","aruna","anil");

list=[Link]().filter(e>[Link]("a")).collect([Link]())
;

for(String list1:list) {
[Link](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 = [Link](
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);

[Link]((department,
maxSalary) -> [Link]("Max salary in department " + department
+ ": " + maxSalary));
}

public static Map<String, Double>


findMaxSalaryByDepartment(List<Employee> employees) {
return [Link]()
.collect([Link](Employee::
getDepartment,

[Link](Employee::getSalary,
[Link](Double::compare))))
.entrySet()
.stream()
.collect([Link](
[Link]::getKey,
entry ->
[Link]().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 = [Link](
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


[Link]([Link]::println);
}

public static List<Employee>


sortEmployeesByDepartmentDescending(List<Employee> employees) {
return [Link]()
.sorted([Link](Employee::getDepar
tment).reversed())
.collect([Link]());
}
}

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 =
[Link](1,2,3,4,4,5,6,7,8);

[Link]().sorted([Link]()).forEach([Link]::
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:

[Link]()
.map(Employee::getDepartment)
.distinct()
.forEach([Link]::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=

[Link]().collect([Link](Employee::getGender,
[Link]()));

[Link](noOfMaleAndFemaleEmployees);

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

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

Map<String, Double> avgAgeOfMaleAndFemaleEmployees=

[Link]().collect([Link](Employee::getGender,
[Link](Employee::getAge)));

[Link](avgAgeOfMaleAndFemaleEmployees);

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

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

Optional<Employee> highestPaidEmployeeWrapper=

[Link]().collect([Link]([Link](E
mployee::getSalary)));

Employee highestPaidEmployee = [Link]();

[Link]("Details Of Highest Paid Employee : ");

[Link]("==================================");

[Link]("ID :
"+[Link]());

[Link]("Name :
"+[Link]());

[Link]("Age :
"+[Link]());

[Link]("Gender :
"+[Link]());

[Link]("Department :
"+[Link]());

[Link]("Year Of Joining :
"+[Link]());

[Link]("Salary :
"+[Link]());

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?

[Link]()
.filter(e -> [Link]() > 2015)
.map(Employee::getName)
.forEach([Link]::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


[Link]((department, count) ->
[Link]("Number of employees in " + department + ": " +
count));
}

public static Map<String, Long>


countEmployeesByDepartment(List<Employee> employees) {
return [Link]()
.collect([Link](Employee::getDepartment,
[Link]()));

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=

[Link]().collect([Link](Employee::getDepartment
));

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


[Link]();

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


[Link]("--------------------------------------");

[Link]("Employees In "+[Link]() + " : ");


[Link]("--------------------------------------");

List<Employee> list = [Link]();

for (Employee e : list) {


[Link]([Link]());
}
}

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 = [Link](1, 2, 3, 4, 5);

[Link]().map(x-> x*2).forEach([Link]::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 = [Link](1, 2, 3, 4, 5);

[Link]().filter(x-> x>2).forEach([Link]::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 = [Link](1, 2, 3, 4, 5);

List<Integer>
list1=[Link]().sorted().collect([Link]());

[Link](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 = [Link](1, 2, 3, 4, 5);

[Link]().sorted([Link]()).forEach([Link]::prin
tln);

//[Link](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 = [Link](1, 2, 3, 4, 5);

long number=[Link]().count();

[Link](number);
}
}

O/P
5

39 Find the each department name in employee list in java8

[Link]().map(Employee::getDepartment).di
stinct().forEach([Link]::println);
40 Find the each employee count in all departments in java8

Map< String,Long>
map=[Link]().collect([Link](Employee::getDepart
ment,[Link]()));

[Link](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

[Link]("First " + n + " Fibonacci numbers:");


fibonacciSequence(n).forEach([Link]::println);
}

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


return [Link](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.

Common questions

Powered by AI

In Java 8, you find the first non-repeated character in a string by converting the string to a stream of characters and then using groupingBy to count occurrences. Create a linked hash map with these counts to maintain the order, filter entries with a count of 1, and obtain the first such character using findFirst()

Use Java 8 Stream API to filter employees by applying a filter that checks if the year of joining is greater than the specified year. Then, map the result to employee names with map(Employee::getName) and print them out using forEach()

Java 8 allows swapping two strings without using a third variable by concatenating the strings, then extracting them based on their lengths. First, append str2 to str1, then update str2 as the substring from the start of the concatenated string to the length of str1. Finally, update str1 as the remaining substring.

To find the second largest number in a list, sort the stream in reverse order and use skip(1) to bypass the first (largest) element. Then fetch the first element of this new stream. This approach identifies the second largest number effectively.

To get department names without duplicates, map the stream to department names using map(Employee::getDepartment). Then use distinct() to eliminate duplicates, finally, forEach to print the unique department names.

To count character occurrences in a string using Java 8 Stream API, convert the string to a character stream using chars(). Then, map each character to an object and collect them into a Map using groupingBy with Function.identity() as the key and Collectors.counting() as the value. This will return a Map with characters as keys and their counts as values.

To find the maximum value in a list of integers using Java 8, use the stream max() method with Integer::compare as the comparator. This returns an Optional containing the maximum value which can be retrieved using get()

You can find duplicate elements in a list of integers using Java 8 Stream functions by leveraging a HashSet to track seen elements. Stream the list and use the filter operation with a condition that checks if an element can be added to the HashSet. If an element cannot be added, it means it's a duplicate, which can then be printed or collected.

To swap two numbers without a third variable, sum them and assign to the first variable, derive the second by subtracting this new sum from the second number, and update the first by subtracting the new second from the sum. This effectively swaps the numbers.

Retrieve the last element of an ArrayList by streaming the list, skipping the size of the list minus one, and using findFirst() to get the last element. This approach works efficiently with streams.

You might also like