Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count how many integer elements in array that are equal in java?

Say I have an array of 3 integers. I want to be able to obtain these results from these arrays using just if statements or a for loop.

[0,1,2] = 0 equal
[0,1,0] = 2 equal
[0,0,0] = 3 equal

This what i have so far and it works, but I think it could be simplified.

int numequal = 0;

if(intarr[0] != null && intarr[1] != null && intarr[0].numequals(intarr[1])) {
    numequal++;
}

if(intarr[0] != null && intarr[2] != null && intarr[0].numequals(intarr[2])) {
    numequal++;
}

if(intarr[1] != null && intarr[2] != null && intarr[1].numequals(intarr[2])) {
    numequal++;
}

if(numequal == 1) {
    numequal = 2;
}

Also, I'm trying to keep it basic. Maybe just for loops. No hash sets or dictionaries.

like image 635
user1859040 Avatar asked Dec 29 '25 17:12

user1859040


2 Answers

You are probably looking for really simple solution so I tried to optimize your code a bit:

int[] intarr = {'0','1','2'};
int numequal = 0; 

if(intarr[0] == intarr[1] || intarr[0] == intarr[2] ){
    numequal++;
}
if( intarr[1] == intarr[2]){
    numequal++;
}

if (numequal > 0 ){
    numequal++;
}

if your array is declared as int[] there is no need to check for nulls
intarr[1] != null.

If some item is not set, it will be default 0

like image 110
d.raev Avatar answered Jan 01 '26 07:01

d.raev


Here is my solution. It is not simple but very efficient. Currently it counts null elements too, which can easily be fixed if it's undesirable.

    Integer[] a = { null, 2, 1, null, 0, 1 };
    Arrays.sort(a, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            if (o1 == null) {
                return -1;
            }
            if (o2 == null) {
                return 1;
            }
            return o1.compareTo(o2);
        }
    });
    // [null, null, 0, 1, 1, 2]
    int n = 0;
    Integer prev = null;
    Boolean first = null;
    for (Integer e : a) {
        if (first != null && (e == prev || e != null && e.equals(prev))) {
            if (first == Boolean.TRUE) {
                n += 2;
                first = Boolean.FALSE;
            } else {
                n++;
            }
        } else {
            first = Boolean.TRUE;
        }
        prev = e;
    }
    System.out.println(n);
like image 25
Evgeniy Dorofeev Avatar answered Jan 01 '26 05:01

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!