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

Updated on: 09-May-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements