- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Simple way to find if two different lists contain exactly the same elements in Java
Two lists are equal if they consist of same number of elements in the same order.
Let’s say we have the following two lists −
List<Integer>arrList1 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100 }); List<Integer>arrList2 = Arrays.asList(new Integer[] {15, 25, 35, 50, 55, 75, 95, 120});
Now, let’s find out whether both the lists are equal or not −
arrList1.equals(arrList2);
If both the above lists have equal elements, then TRUE is returned, else FALSE is the return value.
Example
import java.util.Arrays; import java.util.List; public class Demo { public static void main(String[] a) { List<Integer>arrList1 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100 }); List<Integer>arrList2 = Arrays.asList(new Integer[] {15, 25, 35, 50, 55, 75, 95, 120}); List<Integer>arrList3 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100}); System.out.println("Are List 1 and List2 equal? "+arrList1.equals(arrList2)); System.out.println("Are List 2 and List3 equal? "+arrList2.equals(arrList2)); System.out.println("Are List 1 and List3 equal? "+arrList1.equals(arrList3)); } }
Output
Are List 1 and List2 equal? false Are List 2 and List3 equal? true Are List 1 and List3 equal? true
Advertisements