Question: In java 8. Modify the averageTopSpeed() method (in the class FormulaOne) using only lambdas and streams and print it to the terminal via the driver

In java 8. Modify the averageTopSpeed() method (in the class FormulaOne) using only lambdas and streams and print it to the terminal via the driver class:

import java.util.*;

public class Racer implements Comparable { private final String name; private final int year; private final int topSpeed; public Racer(String name, int year, int topSpeed){ this.name = name; this.year = year; this.topSpeed = topSpeed; } public String toString(){ return name + "-" + year + ", Top speed: " + topSpeed + "km/h"; } public int getTopSpeed(){ return topSpeed; } public int getYear(){ return year; } public String getName(){ return name; } public int compareTo(Racer other){ if(year != other.getYear()){ return year - other.getYear(); } return name.compareTo(other.getName()); } }

public class FormulaOne { private String name; private ArrayList racers; public FormulaOne(String name){ this.name = name; racers = new ArrayList(); } public void add(Racer r){ racers.add(r); } public int averageTopSpeed(){ int sumTop = 0; int sumIt = 0; for(Racer r: racers){ sumTop += r.getTopSpeed(); sumIt++; } int avgTop = sumTop/sumIt; return avgTop;

}

public Racer fastestRacer(){ Racer fastest = null; for(Racer r: racers){ if(fastest == null || fastest.getTopSpeed() < r.getTopSpeed()){ fastest = r; } } return fastest; } public void printFormulaOne(){ System.out.println(name); Collections.sort(racers); for(Racer r: racers){ System.out.println(r); } } }

public class Driver { public static void exam(){ Racer r1 = new Racer("Farrari", 2011, 180); Racer r2 = new Racer("Lada", 2016, 320); Racer r3 = new Racer("Volvo" , 2020, 180); Racer r4 = new Racer("Fiat" , 2016, 250); Racer r5 = new Racer("Toyota", 2000, 160); System.out.println(r1.toString()); System.out.println(r2.toString()); System.out.println(r3.toString()); System.out.println(r4.toString()); System.out.println(r5.toString()); FormulaOne fo = new FormulaOne("Formula One"); fo.add(r1); fo.add(r2); fo.add(r3); fo.add(r4); fo.add(r5); System.out.println(""); System.out.println("Find average topspeed of cars in Formula One: "); System.out.println(averageTopSpeed() + "km/h"); System.out.println(""); System.out.println("Find fastest car in Formula One"); System.out.println(fo.fastestRacer()); System.out.println(""); System.out.println("Alle racerbiler i Formula One sorteres efter produktions r"); fo.printFormulaOne(); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!