Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find number of element in an Array in java?

Tags:

java

arrays

I want to know that how can i find the number of element in the normal array in java. For example if i have an int array with size 10 and i have inserted only 5 element. Now, i want to check the number of element in my array? Below is the code for more clarification. Please help

public static void main(String[] args) {

        int [] intArray = new int[10];
        char [] charArray = new char[10];

        int count = 0;

        for(int i=0; i<=5; i++) {

            intArray[i] = 5;    
            charArray[i] = 'a';


        }


        for(int j=0; j<=intArray.length; j++) {
            if(intArray[j] != null) {
                count++;
            }
        }

        System.out.println("int Array element : "+ count);
    }
like image 675
Vid Avatar asked Mar 17 '23 23:03

Vid


2 Answers

The code is wrong. You declare a int[] : this cannot contain null values so this statement will not compile :

if(intArray[j] != null) {

Then, if you want to store many items but you don't know howmany, you should use a Collection, for example ArrayList

List<Integer> ints = new ArrayList<Integer>(); //Or new ArrayList<>(); - Java7

Then, you can have the size with :

ints.size();

Now, if you really want to use an array, then you can for example count the number of non-zero values :

for(int j=0; j<=intArray.length; j++) {
  if(intArray[j] != 0) {
    count++;
  }
}

Or better in Java 7 :

for(int i : intArray) {
  if(i!=0) {
    count++;
  }
}

Even better in Java 8 :

Arrays.stream(intArray).filter(i -> i !=0).count();
like image 146
Arnaud Denoyelle Avatar answered Apr 01 '23 09:04

Arnaud Denoyelle


Check out Collection.frequency(). This will count how many times the specific Object (in this case null) appears in the Collection.

Below is just an example to help you along

String[] array = new String[5];

array[0] = "This";
array[1] = null;
array[2] = "is";
array[3] = null;
array[4] = "a test";

int count = Collections.frequency(Arrays.asList(array), null);

System.out.println("String: " + count + " items out of " + array.length + " are null");

int[] iArray = new int[3];
iArray[0] = 0;
iArray[1] = 1;
iArray[2] = 2;

List<Integer> iList = new ArrayList<>();

for (int i : iArray) {
    iList.add(i);
}

int iCount = Collections.frequency(iList, 0);

System.out.println("Int: " + iCount + " items out of " + iArray.length + " are zero");

char[] cArray = new char[3];
cArray[0] = 'c';
cArray[1] = ' ';
cArray[2] = 'a';

List<Character> cList = new ArrayList<>();

for (char c : cArray) {
    cList.add(c);
}

int cCount = Collections.frequency(cList, ' ');

System.out.println("Char: " + cCount + " items out of " + cArray.length + " are ' '");

Output:

String: 2 items out of 5 are null
Int: 1 items out of 3 are zero
Char: 1 items out of 3 are ' '

like image 29
Ascalonian Avatar answered Apr 01 '23 08:04

Ascalonian