KaiquanMah's picture
route.getDirection() == direction
095a473 verified
raw
history blame
2.98 kB
The program has defined the Route class written in the previous exercise.
Write a method:
public static ArrayList<Route> routesInDirection(ArrayList<Route> routes, CardinalDirection direction)
which receives a list of route objects and a direction as parameters.
The method returns a new list containing those routes that go in the given direction.
The ORDER of the routes in the new list should be the SAME as in the list provided as a parameter.
import java.util.ArrayList;
import java.util.Random;
public class Test{
public static void main(String[] args){
final Random r = new Random();
ArrayList<Route> al = new ArrayList<>();
int count = r.nextInt(5) + 10;
for (int i = 0; i < count; i++) {
double length = r.nextInt(200) + 10;
CardinalDirection direction = CardinalDirection.values()[r.nextInt(4)];
al.add(new Route(length, direction));
}
System.out.println("All routes:");
al.stream().forEach(rt -> System.out.println("" + rt));
for (CardinalDirection direction : CardinalDirection.values()) {
System.out.println("");
System.out.println("Routes in the direction " + direction);
ArrayList<Route> al2 = routesInDirection(al, direction);
al2.stream().forEach(rt -> System.out.println("" + rt));
}
}
//add
public static ArrayList<Route> routesInDirection(ArrayList<Route> routes, CardinalDirection direction) {
// initialise empty ArrayList
// approach 1 - works
ArrayList<Route> filteredRoutes = new ArrayList<Route>();
// approach 2 - works
// in Java 7+
// ArrayList<Route> filteredRoutes = new ArrayList<>();
for (Route route: routes) {
if (route.getDirection() == direction) {
filteredRoutes.add(route);
}
}
return filteredRoutes;
}
}
All routes:
Direction: NORTH, length: 125.0
Direction: WEST, length: 160.0
Direction: NORTH, length: 114.0
Direction: NORTH, length: 196.0
Direction: NORTH, length: 167.0
Direction: NORTH, length: 169.0
Direction: WEST, length: 120.0
Direction: EAST, length: 124.0
Direction: WEST, length: 34.0
Direction: NORTH, length: 173.0
Direction: EAST, length: 107.0
Direction: WEST, length: 167.0
Direction: NORTH, length: 95.0
Routes in the direction NORTH
Direction: NORTH, length: 125.0
Direction: NORTH, length: 114.0
Direction: NORTH, length: 196.0
Direction: NORTH, length: 167.0
Direction: NORTH, length: 169.0
Direction: NORTH, length: 173.0
Direction: NORTH, length: 95.0
Routes in the direction SOUTH
Routes in the direction EAST
Direction: EAST, length: 124.0
Direction: EAST, length: 107.0
Routes in the direction WEST
Direction: WEST, length: 160.0
Direction: WEST, length: 120.0
Direction: WEST, length: 34.0
Direction: WEST, length: 167.0