In: Computer Science
/*
* Returns a new array of students containing only
those students from the given roster that belong
* to the given academic program
* The resulting array must not contain any null
entries
* Returns empty array (length == 0) if no students
belong to the program
*/
public static UStudent[] filterByProgram(String
program, UStudent[] roster) {
//YOUR CODEf
int counter=0;
for(int i=0;i<roster.length;i++)
{
if(roster[i].getAcademicProgram().equals(program)) {
counter++;
UStudent[] Studentbelongprogram = new
UStudent[counter];
Studentbelongprogram[i]=roster[i];
roster=Studentbelongprogram;
}else {
return new UStudent[0];
}
}
return roster;
}
Use the following code snippet to achieve the goal:
I have used Java Stream API to achieve this. Filtered out any null values and next filter will shortlist the matching elements.
public static UStudent[] filterByProgram(String program, UStudent[]
roster) {
UStudent[] result = Arrays.stream(roster)
.filter(x -> x!=null)
.filter(x -> x.getAcademicProgram().equals(program))
.collect(Collectors.toList()).stream().toArray(UStudent[]::new);
return result;
}
==============================================================================================
Do not forget to add imports
==========================================================================================
import java.util.*;
import java.util.stream.Collectors;
=========================================================================================