Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: array if all the same

Tags:

java

I have a array:

int tarningar[] = new int[5];

That holds numbers. When all the numbers are the same, system.out.println('ok');

How can I do this?

like image 745
Karem Avatar asked Dec 15 '10 10:12

Karem


2 Answers

Here's a more succinct Java 8 streams example:

Arrays.stream(tarningar).distinct().count() == 1
like image 168
Matthew Avatar answered Oct 12 '22 21:10

Matthew


boolean flag = true;
int first = tarningar[0];
for(int i = 1; i < 5 && flag; i++)
{
  if (tarningar[i] != first) flag = false;
}
if (flag) System.out.println("ok");
like image 42
Boris Pavlović Avatar answered Oct 12 '22 20:10

Boris Pavlović