1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| class Car{ private String make; private String model; private int year;
public Car(String make, String model, int year) { this.make = make; this.model = model; this.year = year; }
public String getMake() { return make; }
public String getModel() { return model; }
public int getYear() { return year; } }
public class Main { public static void main(String[] args) throws InterruptedException { List<Car> cars = Arrays.asList( new Car("Jeep", "Wrangler", 2011), new Car("Jeep", "Comanche", 1990), new Car("Dodge", "Avenger", 2010), new Car("Buick", "Cascada", 2016), new Car("Ford", "Focus", 2012), new Car("Chevrolet", "Geo Metro", 1992) ); System.out.println(getModelsAfter2000UsingFor(cars)); System.out.println(getModelsAfter2000UsingForNew(cars)); }
public static List<String> getModelsAfter2000UsingFor(List<Car> cars){ List<Car> sortCar = new ArrayList<>(); for (Car car : cars) { if (car.getYear() > 2000){ sortCar.add(car); } } sortCar.sort(new Comparator<Car>() { @Override public int compare(Car o1, Car o2) { return Integer.valueOf(o1.getYear()).compareTo(o2.getYear()); } }); List<String> models = new ArrayList<>(); for (Car car : sortCar) { models.add(car.getModel()); } return models; } public static List<String> getModelsAfter2000UsingForNew(List<Car> cars){
return cars.stream() .filter(car -> car.getYear() > 2000) .sorted(Comparator.comparing(Car::getYear)) .map(Car::getModel) .collect(Collectors.toList()); }
}
|