

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
- Related Questions & Answers
- Python - Check if all elements in a List are same
- JavaScript Checking if all the elements are same in an array
- Python - Check if all elements in a list are identical
- Python Pandas - Determine if two CategoricalIndex objects contain the same elements
- Determine if two filename paths refer to the same File in Java
- How to remove all elements from a Java List?
- How to determine if the string has all unique characters using C#?
- How to determine if jQuery effects are still executing?
- Check if list contains all unique elements in Python
- How do I remove all elements from a list in Java?
- How to multiply matrices elements if matrices are stored in a list in R?
- Determine if a Preference Node exists in Java
- How to print text from a list of all web elements with same class name in Selenium?
- C# program to determine if a string has all unique characters
- Check if all array elements are distinct in Python
Advertisements