Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java all determine elements are same in a list

I am trying to determine to see if all elements in a list are same. such as:

(10,10,10,10,10) --> true (10,10,20,30,30) --> false 

I know hashset might be helpful, but i don't know how to write in java.

this is the one I've tried, but didn't work:

public static boolean allElementsTheSame(List<String> templist)  {      boolean flag = true;     String first = templist.get(0);      for (int i = 1; i< templist.size() && flag; i++)     {         if(templist.get(i) != first) flag = false;     }      return true; } 
like image 385
Colin Zhong Avatar asked Mar 26 '15 20:03

Colin Zhong


People also ask

How do you check if all the values are same in list Java?

allMatch() method. The allMatch() method returns true if all elements of the stream matches with the given predicate. It can be used as follows to check if all elements in a list are the same.

How do you check if all the elements of a list are equal?

You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.

How do you check if two elements in a list are the same Java?

List equals() Method in Java with Examples. This method is used to compare two lists. It compares the lists as, both lists should have the same size, and all corresponding pairs of elements in the two lists are equal. Parameters: This function has a single parameter which is object to be compared for equality.


1 Answers

Using the Stream API (Java 8+)

boolean allEqual = list.stream().distinct().limit(2).count() <= 1 

or

boolean allEqual = list.isEmpty() || list.stream().allMatch(list.get(0)::equals); 

Using a Set:

boolean allEqual = new HashSet<String>(tempList).size() <= 1; 

Using a loop:

boolean allEqual = true; for (String s : list) {     if(!s.equals(list.get(0)))         allEqual = false; } 

Issues with OP's code

Two issues with your code:

  • Since you're comparing Strings you should use !templist.get(i).equals(first) instead of !=.

  • You have return true; while it should be return flag;

Apart from that, your algorithm is sound, but you could get away without the flag by doing:

String first = templist.get(0); for (int i = 1; i < templist.size(); i++) {     if(!templist.get(i).equals(first))         return false; } return true; 

Or even

String first = templist.get(0); for (String s : templist) {     if(!s.equals(first))         return false; } return true; 
like image 194
aioobe Avatar answered Sep 18 '22 18:09

aioobe