Question

In java 8. Modify the averageTopSpeed() method (in the class FormulaOne) using only lambdas and streams...

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();
  
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code : i have only modified the averageTopSpeed() method (in the class FormulaOne) using only lambdas and streams as asked in question and printed the output by using Driver mehtod of the Driver class. Changed the name of method in Driver class to test() as HomeworkLib editor is giving error for that input.

import java.util.*;
import java.util.stream.Collectors;

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(Object o) {
        return 0;
    }

    public int compareTo(Racer other){
        if(year != other.getYear()){
            return year - other.getYear();
        }

        return name.compareTo(other.getName());

    }


}

class FormulaOne
{
    private String name;
    private List<Racer> racers;

    public FormulaOne(String name){

        this.name = name;
        racers = new ArrayList();

    }

    public void add(Racer r){

        racers.add(r);

    }

    public int averageTopSpeed(){
        //modifying with java 8 lambda expression
        /* here we are taking the racers list element one by one by using .stream() */
        /* after stream conversion we are using .collect() to collect the output of the list*/
        /* in .collect as paramter we calculate the avergae of the list top speed by using
        * Collectors .averagingInt method having the TopSpeed of every list element as parameter one by one
        * .avergingInt() basically sum all the speed and calculate average from it*/

        Double averageSpeed = racers
                .stream()
                .collect(Collectors.averagingInt(p -> p.getTopSpeed()));
        return averageSpeed.intValue(); /*output is in Double by out method output is int so
​                                          converting the same*/


    }

    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);

        }


    }

}
class Driver
{
    public static void test(){

        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(fo.averageTopSpeed() + "km/h");  // this will print the average of top speed

        System.out.println("");
        System.out.println("Find fastest car in Formula One");
        System.out.println(fo.fastestRacer()); //this print the fastest car

        System.out.println("");
        System.out.println("Alle racerbiler i Formula One sorteres efter produktions år");
        fo.printFormulaOne();  //this print all formula one

    }

    public static void main(String a[]){
        test(); /* this call the test method of driver to print the speed,average speed, fastest speed */
    }
}


OutPut :-

The averge speed output is highlighted

Run Driver : Program Files 1Javaljdk1.8.0131bin1java Farrari-2011, Top speed: 180km/h Lada-2016, Top speed: 320km/h | Volvo-2

Main changes in code :-

import statement

average speed:-

public int averageTopSpeed ) //modifying with java 8 lambda expression /1 here ve are taking the racers list element one by o

Add a comment
Know the answer?
Add Answer to:
In java 8. Modify the averageTopSpeed() method (in the class FormulaOne) using only lambdas and streams...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Below are the Car class and Dealership class that I created In the previous lab import...

    Below are the Car class and Dealership class that I created In the previous lab import java.util.ArrayList; class Car { private String make; private String model; private int year; private double transmission; private int seats; private int maxSpeed; private int wheels; private String type; public Car() { } public Car(String make, String model, int year, double transmission, int seats, int maxSpeed, int wheels, String type) { this.make = make; this.model = model; this.year = year; this.transmission = transmission; this.seats =...

  • How to solve and code the following requirements (below) using the JAVA program? 1. Modify the...

    How to solve and code the following requirements (below) using the JAVA program? 1. Modify the FoodProduct Class to implement Edible, add the @Overrride before any methods that were there (get/set methods) that are also in the Edible interface. 2. Modify the CleaningProduct Class to implement Chemical, add the @Overrride before any methods that were there (get/set methods) that are also in the Chemical interface. 3. Create main class to read products from a file, instantiate them, load them into...

  • Copy all the classes given in classes Calendar, Day, Month, & Year into BlueJ and then...

    Copy all the classes given in classes Calendar, Day, Month, & Year into BlueJ and then generate their documentation. Examine the documentation to see the logic used in creating each class. (Code given below) import java.util.ArrayList; import java.util.Iterator; class Calendar { private Year year; public Calendar() { year = new Year(); } public void printCalendar() { year.printCalendar(); } } class Year { private ArrayList<Month> months; private int number; public Year() { this(2013); } public Year(int number) { this.number = number;...

  • Solve this using Java for an Intro To Java Class. Provided files: Person.java /** * Models...

    Solve this using Java for an Intro To Java Class. Provided files: Person.java /** * Models a person */ public class Person { private String name; private String gender; private int age; /** * Consructs a Person object * @param name the name of the person * @param gender the gender of the person either * m for male or f for female * @param age the age of the person */ public Person(String name, String gender, int age) {...

  • JAVA Modify the code to create a class called box, wherein you find the area. I...

    JAVA Modify the code to create a class called box, wherein you find the area. I have the code in rectangle and needs to change it to box. Here is my code. Rectangle.java public class Rectangle { private int length; private int width;       public void setRectangle(int length, int width) { this.length = length; this.width = width; } public int area() { return this.length * this.width; } } // CONSOLE / MAIN import java.awt.Rectangle; import java.util.Scanner; public class Console...

  • I have a little problem about my code. when i'm working on "toString method" in "Course"...

    I have a little problem about my code. when i'm working on "toString method" in "Course" class, it always say there is a mistake, but i can not fix it: Student class: public class Student {    private String firstName;    private String lastName;    private String id;    private boolean tuitionPaid;       public Student(String firstName, String lastName, String id, boolean tuitionPaid)    {        this.firstName=firstName;        this.lastName=lastName;        this.id=id;        this.tuitionPaid=tuitionPaid;    }   ...

  • Modify the objectstudent JAVA program to add a private variable zipcode, you must also add setters...

    Modify the objectstudent JAVA program to add a private variable zipcode, you must also add setters and getter methods for the new variable and modify the toString method. The objectstudent program is in this weeks module, you can give it a default value of 19090. class Student { private int id; private String name; public Student() { id = 8; name = "John"; } public int getid() { return id; } public String getname() { return name; } public void...

  • java programming how would i modify the code below to add a GUI (with a main menu with graphics and buttons, etc...) and include an option to print a list of all students added in a grid format and sh...

    java programming how would i modify the code below to add a GUI (with a main menu with graphics and buttons, etc...) and include an option to print a list of all students added in a grid format and short by name, course, instructor, and location. ///main public static void main(String[] args) { Scanner in = new Scanner(System.in); ArrayList<Student>students = new ArrayList<>(); int choice; while(true) { displayMenu(); choice = in.nextInt(); switch(choice) { case 1: in.nextLine(); System.out.println("Enter Student Name"); String name...

  • JAVA help Create a class Individual, which has: Instance variables for name and phone number of...

    JAVA help Create a class Individual, which has: Instance variables for name and phone number of individual. Add required constructors, accessor, mutator, toString() , and equals method. Use array to implement a simple phone book , by making an array of objects that stores the name and corresponding phone number. The program should allow searching in phone book for a record based on name, and displaying the record if the record is found. An appropriate message should be displayed if...

  • In Java Create a testing class that does the following to the given codes below: To...

    In Java Create a testing class that does the following to the given codes below: To demonstrate polymorphism do the following: Create an arraylist to hold 4 base class objects Populate the arraylist with one object of each data type Code a loop that will process each element of the arraylist Call the first ‘common functionality’ method Call the second ‘common functionality’ method Call the third ‘common functionality’ method Verify that each of these method calls produces unique results Call...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT