I understand that there's a similar question: How can I check whether an array is null / empty?. But what I am keen to find out is if there are any ways to check if an array is empty without the use of null or additional java libraries. (The only java library allowed would be java.lang.)
Say for example in jshell:
jshell> int[] array = new int[10]
array ==> int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
Such would be an instance of the empty array that I am refering to.
I could use a loop to check if all the entries are 0,
for(int j = 0; j < array.length; j ) {
if (j != 0) {
return "Not Empty!";
}
}
but I'm wondering if there's a more efficient way.
Would appreciate any insights on this!
CodePudding user response:
you could use streams
in jdk8
boolean allZero = Arrays.stream(
new Integer[]{ 0, 0, 0 } // you array
).allMatch(i -> i == 0);
boolean noneZero = Arrays.stream(
new Integer[]{ 1,1,1 } // you array
).noneMatch(i -> i == 0);
boolean containsZero = Arrays.stream(
new Integer[]{ 1,0,1 } // you array
).anyMatch(i -> i == 0);
List already has stream()
in jdk8 and List.of()
has in jdk11
List.of(1,2,3).stream().allMatch(...);
CodePudding user response:
If you define empty as only containing 0 then you iterate over the array. If any element is not zero then you return false immediately. If you traverse the array without return false then you return true. There are numerous ways to traverse the arrays.
Traditional for loop:
public boolean onlyZeros(int[] array) {
for (int index = 0 ; index < array.length ; index) {
if (array[index] != 0) {
return false;
}
}
return true;
}
For-each loop:
public boolean onlyZeros(int[] array) {
for (int e : array) {
if (e != 0) {
return false;
}
}
return true;
}
Stream:
public boolean onlyZeros(int[] array) {
return !(Arrays.stream(array)
.filter(e -> e != 0)
.findAny()
.isPresent());
}
CodePudding user response:
If the input array is rather small, a plain for
loop should be the most efficient way to detect a non-zero element and iteration may take place from both head and tail of the array:
public static boolean allZeros(int ... arr) {
if (arr.length == 0) return true;
for (int i = 0, n = arr.length, mid = n >> 1; i <= mid; i ) {
if (arr[i] != 0 || arr[n - 1 - i] == 0) return false;
}
return true;
}
If the array is quite big, a solution using parallel stream may be more performing:
public static boolean allZerosStream(int ... arr) {
return Arrays.stream(arr) // sequential IntStream
.parallel() // parallel IntStream
.allMatch(x -> 0 == x); // or .anyMatch(x -> 0 != x)
}
However, both these approaches require proper benchmarking.