1Z0-809 · Question #213
Given: `` public class Vehicle { int vid; String vName; public Vehicle(int vIdArg, String vNameArg) { this.vid = vIdArg; this.vName = vNameArg; } public int getVId() { return vid; } public String…
The correct answer is D. .sorted((v1, v2) -> Integer.compare(v1.getVId(), v2.getVId())). Option D (Integer.compare(v1.getVId(), v2.getVId())) correctly sorts vehicles ascending by vid (1→2→3), producing Truck→Car→Bike. Since toString() returns vName, forEach(System.out::print) outputs TruckCarBike. Note that the question asks for two correct answers - Option A is…
Question
public class Vehicle {
int vid;
String vName;
public Vehicle(int vIdArg, String vNameArg) {
this.vid = vIdArg;
this.vName = vNameArg;
}
public int getVId() { return vid; }
public String getVName() { return vName; }
public String toString() { return vName; }
}
and the code fragment:
List<Vehicle> vehicle = Arrays.asList(
new Vehicle(2, "Car"),
new Vehicle(3, "Bike"),
new Vehicle(1, "Truck"));
vehicle.stream()
// line n1
.forEach(System.out::print);
Which two code fragments, when inserted at line n1 independently, enable the code to print TruckCarBike?Options
- A.sorted((v1, v2) -> v1.getVId() - v2.getVId())
- B.sorted(Comparable.comparing(Vehicle::getVName()).reversed())
- C.map(v -> v.getVId())
- D.sorted((v1, v2) -> Integer.compare(v1.getVId(), v2.getVId()))
- E.sorted(Comparator.comparing((Vehicle v) -> v.getVId()))
How the community answered
(52 responses)- A10% (5)
- B2% (1)
- C4% (2)
- D85% (44)
Explanation
Option D (Integer.compare(v1.getVId(), v2.getVId())) correctly sorts vehicles ascending by vid (1→2→3), producing Truck→Car→Bike. Since toString() returns vName, forEach(System.out::print) outputs TruckCarBike. Note that the question asks for two correct answers - Option A is also correct, as the lambda subtraction v1.getVId() - v2.getVId() produces equivalent ascending sort results for small positive integers (though it risks integer overflow with extreme values, making D the safer idiom).
Why the others fail:
- B -
Comparable.comparing()doesn't exist; the correct class isComparator. The method reference syntaxVehicle::getVName()with parentheses is also illegal. - C -
.map(v -> v.getVId())transforms the stream intoStream<Integer>, discarding vehicle names entirely, and performs no sorting - it would print123, not vehicle names. - E -
Comparator.comparing((Vehicle v) -> v.getVId())actually does work and sorts ascending by vId, so exam takers should flag this as potentially a third valid answer; exam versions vary on whether E is included.
Memory tip: When sorting a stream by an int field, prefer Integer.compare(a.getX(), b.getX()) over subtraction - it's overflow-safe and reads clearly. Associate Comparator (with an o) with .comparing(), not Comparable (which defines the natural order on the object itself).
Community Discussion
No community discussion yet for this question.