1

How do I check how many elements have values? yes, this can also include how to check if an element has a value.

String[] Array = new String[50]; //initialization

Array[i] = "1"; // Array[0]

Array[] = "2"; // Array[1]

how can I know that 2 out of 50 elements have values?

(read about ArrayList. my app keeps crashing when I'm retrieving and displaying it.)

0

3 Answers 3

1

You could check which elements aren't null:

long numWithValue = Arrays.stream(array).filter(Objects::nonNull).count();

EDIT:
If you can't use Java 8 syntax, you can always use an old fashioned loop:

int numWithValue = 0;
for (int i = 0; i < array.length; ++i){ 
    if (array[i] != null) {
        ++numWithValue;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

(Object::nonNull) : Method references are not supported at this language level (i'm using api 15) stream(arr) : cannot resolve symbol
@Ray I really suggest you use a newer version of the API. Regardless of this recommendation, check out my edited answer for a solution that would work for older versions.
0

You can use this

int count=0;
for(int i=0;i<Array.length;i++)
if(!(Array[i]==null))
count++;

count is the number of elements that have been initialised.

Comments

0
 long numWithValue = arr.length - Collections.frequency(Arrays.asList(arr), null);

try this, should be compiled for 1.5 JDK

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.