Challenge: Selecting the Best Cars on the Production Line
Task
Swipe to start coding
At the factory, you need to process a list of cars, filter them based on mileage, sort them according to specific criteria, and display the results.
Each car is represented by the Car
class, which contains an id
as a unique identifier, a model
specifying the car’s name, a year
indicating when it was manufactured, and a mileage
field representing the total distance it has traveled.
- Filter the cars, keeping only those with a mileage of 30,000 miles or less using the
filter()
method. - Sort the cars by
year
in ascending order usingcomparingInt()
method. - Once the cars are sorted by
year
, reverse the order to have the newest cars first usingreversed()
method. - If two cars have the same
year
, sort them bymileage
in ascending order usingthenComparing()
method. - Convert each car object to a string representation, using the
toString()
method. - Print the final list to the console, using a method reference to
println()
.
Solution
solution
99
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
package com.example;
import java.util.List;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
List<Car> cars = List.of(
new Car(1, "Toyota Camry", 2022, 12000),
new Car(2, "Ford Mustang", 2020, 45000),
new Car(3, "Tesla Model 3", 2022, 6000),
new Car(4, "Chevrolet Malibu", 2019, 32000),
new Car(5, "Honda Accord", 2020, 25000)
);
List<String> processedCars = cars.stream()
.filter(car -> car.getMileage() <= 30000)
.sorted(Comparator.comparingInt(Car::getYear).reversed()
.thenComparingInt(Car::getMileage))
.map(Car::toString)
.toList();
processedCars.forEach(System.out::println);
}
}
class Car {
private int id;
private String model;
private int year;
private int mileage;
public Car(int id, String model, int year, int mileage) {
this.id = id;
this.model = model;
this.year = year;
Everything was clear?
Thanks for your feedback!
Section 2. Chapter 6
99
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
package com.example;
import java.util.List;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
List<Car> cars = List.of(
new Car(1, "Toyota Camry", 2022, 12000),
new Car(2, "Ford Mustang", 2020, 45000),
new Car(3, "Tesla Model 3", 2022, 6000),
new Car(4, "Chevrolet Malibu", 2019, 32000),
new Car(5, "Honda Accord", 2020, 25000)
);
List<String> processedCars = cars.stream()
.filter(car -> ___ <= 30000)
.sorted(Comparator.comparingInt(___).___
.thenComparingInt(___))
.map(___)
.toList();
processedCars.forEach(___);
}
}
class Car {
private int id;
private String model;
private int year;
private int mileage;
public Car(int id, String model, int year, int mileage) {
this.id = id;
this.model = model;
Ask AI
Ask anything or try one of the suggested questions to begin our chat