
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse Integer Array Using Lambda Expressions in Java
In this article, we will learn to get the reverse of an Integer array with Lambda expressions in Java. By utilizing the Arrays.sort() method along with a custom comparator defined as a lambda expression, we can efficiently reorder the elements of the array in descending order. Lambda expressions are a concise way to represent functional interfaces, allowing you to write cleaner and more readable code.
Problem Statement
Write a program in Java to get the reverse of an Integer array with Lambda expressions ?
Input
arr = {20, 50, 75, 100, 120, 150, 170, 200}
Output
Integer Array elements...
20
50
75
100
120
150
170
200
Reverse of Array elements...
[200, 170, 150, 120, 100, 75, 50, 20]
Steps to get the reverse of an Integer array
Following are the steps to get the reverse of an Integer array with Lambda expressions ?
- First, we will import the Arrays class from java.util package.
- Initialize the array with some integer values.
- Print the elements of the original array.
- We will use the Arrays.sort() method with a lambda expression to sort the array in descending order.
- Print the elements of the reversed array.
Java program to get the reverse of an Integer array
The following is an example of reversing an Integer array with Lambda expressions ?
import java.util.Arrays; public class Demo { public static void main(String[] args) { Integer[] arr = {20, 50, 75, 100, 120, 150, 170, 200}; System.out.println("Integer Array elements..."); for (int res : arr) { System.out.println(res); } Arrays.sort(arr, (Integer one, Integer two) -> { return (two- one); }); System.out.println("Reverse of Array elements..."); System.out.println(Arrays.toString(arr)); } }
Output
Integer Array elements... 20 50 75 100 120 150 170 200 Reverse of Array elements... [200, 170, 150, 120, 100, 75, 50, 20]
Code explanation
The above program, starts by declaring and initializing an Integer array. It then prints the original array elements. To reverse the array, the Arrays.sort() method is called, passing a lambda expression as a custom comparator. This expression sorts the array in descending order by comparing two elements and rearranging them accordingly. Finally, the program prints the reversed array, showcasing the sorted elements in descending order.