I would like to write a method which returns an array containing only the numbers from input
that are greater than or equal to n
.
So far I have the following:
public static int[] filter(int[] input, int n) {
int counter = 0;
int[] res = new int[input.length];
for(int i = 0; i < input.length; i++) {
if(input[i] >= n) {
res[counter++] = input[i];
}
}
return res;
}
I am aware that int[] res = new int[input.length]
is incorrect because it initialises the array with the size of the input array, but I cannot get it to work otherwise.
As a result, for int[] input = {4,3,2,5,1,6}
and int n = 3
I get 4 3 5 6 0 0
.
I presume it has something to do with the counter and I tried int[] res = new int[counter]
but since counter = 0
it has length 0.
My question: how can I initialise the array res
when I don't know how large it will be?
3 Answers 3
- Shorten: use java 8
Stream
API
public static int[] filter(int[] input, int n) {
return IntStream.of(input).filter(i -> i >= n).toArray();
}
- Easiest: use a non-fixed size wrapper, like a
List
public static Integer[] filter(int[] input, int n) {
List<Integer> res = new ArrayList<>();
for (int val : input) {
if (val >= n) {
res.add(val);
}
}
return res.toArray(new Integer[0]);
}
- Arrays only: copy the needed value into an array with the appropriate size
public static int[] filter(int[] input, int n) {
int counter = 0;
int[] res = new int[input.length];
for (int val : input) {
if (val >= n) {
res[counter++] = val;
}
}
int[] result = new int[counter];
System.arraycopy(res, 0, result, 0, counter);
return result;
}
The System.arraycopy
line can be replaced by
for (int i = 0; i < counter; i++) {
result[i] = res[i];
}
4 Comments
List
? We are not allowed to use such classes in my programming course and so we have to get around things like that with loops.System.arraycopy
?Don’t create the array; let the JDK do it for you:
public static int[] filter(int[] input, int n) {
return Arrays.stream(input)
.filter(i -> i >= n)
.toArray();
}
It’s a lot less code too.
1 Comment
Try ArrarList as follows:
import java.util.ArrayList; //
ArrayList<String> res = new ArrayList<String>();
List
when you need not-fixed size container :) look about ArrayList. Without that you need at the end to create a new array (3rd one) with the size you need, then copy the too-long array into the 3rd one