java: array if all the same

0 votes
asked Dec 15, 2010 by karem

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?

7 Answers

0 votes
answered Dec 15, 2010 by andreas-d

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
answered Dec 15, 2010 by jesper

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
answered Dec 15, 2010 by mudassir
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
answered Dec 15, 2010 by ralph
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
answered Dec 25, 2014 by kanbagoly

with Google's Guava:

boolean allEqual = Sets.newHashSet(Ints.asList(tarningar)).size() == 1;
0 votes
answered Dec 21, 2016 by matthew

Here's a more succinct Java 8 streams example:

Arrays.stream(tarningar).distinct().count() == 1
0 votes
answered Dec 27, 2016 by sevenforce

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;    
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...