I am trying to get every value from the data array that is above my threshold, and put the values from data array that are above the threshold into a new array.
I found a way to do it but I am using two for loops, that are almost similar. So I am wondering if there is a way to do it without the two loops.
public int[] getValuesAboveThreshold(int threshold) {
int counter = 0;
int count =0;
for (int i = 0; i < data.length;i ) {
if(data[i] > threshold) {
counter ;
}
}
int [] thresholdArray = new int [counter];
for(int i =0; i <data.length;i ) {
if(data[i] > threshold) {
thresholdArray[count] = data[i];
count ;
}
}
return thresholdArray;
}
CodePudding user response:
You can do this very easily with a Stream:
public static void main(String[] args) {
int threshold = 4;
int[] data = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] filteredArray = getValuesAboveThreshold(data, threshold);
System.out.println(Arrays.toString(filteredArray));
}
private static int[] getValuesAboveThreshold(int[] originalArray, int threshold) {
return Arrays.stream(originalArray)
.filter(val -> val > threshold)
.toArray();
}
CodePudding user response:
public Collection<Integer> getValuesAboveThreshold(int threshold) {
final Collection<Integer> datasWhichAreGreaterThanThreshold = new ArrayList<>();
for (int i = 0; i < datas.length;i ) {
final int currentData = datas[i];
if(currentData > threshold)
datasWhichAreGreaterThanThreshold.add(currentData);
}
return datasWhichAreGreaterThanThreshold;
}
public Integer[] getValuesAboveThreshold(int threshold) {
final Collection<Integer> datasWhichAreGreaterThanThreshold = new ArrayList<>();
for (int i = 0; i < datas.length;i ) {
final int currentData = datas[i];
if(currentData > threshold)
datasWhichAreGreaterThanThreshold.add(currentData);
}
return datasWhichAreGreaterThanThreshold.toArray(Integer[]::new);
}
NOTE: Your solution does not contain inner loops. Hence, the complexity is Q(n) already. [no matter how many other loops are used] -- performance would be approximately same with exactly one loop solution for large number of datas.