- 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
How to determine if all elements are the same in a Java List?
You can check all elements of a list to be same using streams easily in two steps −
Get the first element.
String firstItem = list.get(0);
Iterate the list using streams and use allMatch() method to compare all elements with the first element.
boolean result = list.stream().allMatch(i -> i.equals(firstItem));
Example
Following is the example showing the use of streams to check elements of the list being same −
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class CollectionsDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList("A", "A", "A", "A", "A")); System.out.println("List: " + list); String firstItem = list.get(0); boolean result = list.stream().allMatch(i -> i.equals(firstItem)); System.out.println("All elements are same: " + result); list.add("B"); System.out.println("List: " + list); result = list.stream().allMatch(i -> i.equals(firstItem)); System.out.println("All elements are same: " + result); } }
Output
This will produce the following result −
List: [A, A, A, A, A] All elements are same: true List: [A, A, A, A, A, B] All elements are same: false
Advertisements