65.1k views
3 votes
Create a class named "Laptop". In the following class, there are four instance variables. Name (type string), brand (type string), model_number (type string), and menefactureing_year (type int). Create a class named "LaptopMain" and the following class adds some data into the ArrayList. The type of ArrayList is Laptop. Now, write a java program to compare the values based on the name and menefatureing_year then print the value in the console.

1 Answer

5 votes

Final Answer:

```java

// Create Laptop and LaptopMain classes, add data to ArrayList, and compare/sort by name and manufacturing year.

Collections.sort(laptops, Comparator.comparing(Laptop::getName).thenComparing(Laptop::getManufacturingYear));

```

Step-by-step explanation:

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

class Laptop {

String name, brand, model_number;

int manufacturing_year;

Laptop(String name, String brand, String model_number, int manufacturing_year) {

this.name = name;

this.brand = brand;

this.model_number = model_number;

this.manufacturing_year = manufacturing_year;

}

}

class LaptopMain {

public static void main(String[] args) {

ArrayList<Laptop> laptops = new ArrayList<>();

// Add data to the ArrayList here

// Compare based on name and manufacturing_year

Collections.sort(laptops, Comparator.comparing(Laptop::getName).thenComparing(Laptop::getManufacturingYear));

// Print the sorted values

for (Laptop laptop : laptops) {

System.out.println("Name: " + laptop.name + ", Manufacturing Year: " + laptop.manufacturing_year);

}

}

}

In this Java program, a class named `Laptop` is created with instance variables for name, brand, model number, and manufacturing year. Another class, `LaptopMain`, adds data to an ArrayList of type Laptop and then compares the values based on name and manufacturing year using the `Collections.sort` method with a custom comparator. The sorted values are then printed to the console.

This program demonstrates the use of classes, ArrayLists, and sorting based on multiple criteria in Java.

User Jakub Kaleta
by
8.1k points