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?

0 votes

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?

0 votes

*All values are the same* is equivalent to *All values are equal to any selected value*.

So just choose one as a *reference* and compare this chosen value to all other values.

0 votes

Simple solution without a loop (and a fixed array length of 5):

```
int v = tarningar[0];
if (tarningar[1] == v && tarningar[2] == v && tarningar[3] == v && tarningar[4] == v) {
System.out.println("All the same!");
}
```

0 votes

```
boolean isSame = true;
for(int i = 1; i < tarningar.length; i++) {
if (tarningar[i] != tarningar[0]) {
isSame = false;
}
}
if (isSame) {
System.out.println("OK");
}
```

0 votes

```
import java.util.Arrays;
/**
* Don't take it serious.
* But it works.
*/
public class Demo {
public static boolean isAllSame(int... numbers) {
int[] firstItemArray = new int[numbers.length];
Arrays.fill(firstItemArray, numbers[0]);
return Arrays.equals(numbers, firstItemArray);
}
public static void main(String[] args) {
System.out.println(isAllSame(1,1,1,1));
System.out.println(isAllSame(1,1,1,2));
}
}
```

0 votes

0 votes

0 votes

In Java 8 with the stream API:

```
Set<Integer> uniqueValues = Arrays.stream(tarningar)
.boxed()
.collect(Collectors.toSet());
boolean allEqual = uniqueValues.size() == 1;
```

If you used `Integer[]`

instead of `int[]`

the following is supported in Java 7 and before:

```
// Integer[] tarninagr = ...
Set<Integer> uniqueValues = new HashSet<>(Arrays.asList(tarningar));
boolean allEqual = uniqueValues.size() == 1;
```

...