In Mobile class, I implement Comparable Interface and override it's compareTo() method to write default/natural sorting.
Mobile.java
package com.company.collections;
public class Mobile implements Comparable<Mobile>{
private String brand;
private int price;
private int ram;
private int rating;
public Mobile(String brand, int price, int ram, int rating) {
super();
this.brand = brand;
this.price = price;
this.ram = ram;
this.rating = rating;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
@Override
public String toString() {
return this.brand + " - " + this.price + " - " + this.ram + " - " + this.rating;
}
public void setPrice(int price) {
this.price = price;
}
public int getRam() {
return ram;
}
public void setRam(int ram) {
this.ram = ram;
}
public int getRating() {
return this.rating;
}
public void setRating(int rating) {
this.rating = rating;
}
@Override
public int compareTo(Mobile mobile) {
return mobile.price - this.price;
}
}
In CompareRam class, then I implement Comparator Interface and override it's compare() method to write alternative/custom sorting for Ram.
CompareRam.java
package com.company.collections;
import java.util.Comparator;
public class CompareRam implements Comparator<Mobile>{
@Override
public int compare(Mobile a, Mobile b) {
return a.getRam() - b.getRam();
}
}
In CompareLogic class, I also implement Comparator Interface and override it's compare() method to write alternative/custom sorting for Rating.
CompareLogic.java
package com.company.collections;
import java.util.Comparator;
public class CompareLogic implements Comparator<Mobile>{
@Override
public int compare(Mobile a, Mobile b) {
return a.getRating() - b.getRating();
}
}
Main.java
package com.company.collections;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<Mobile> arr = new ArrayList<>();
arr.add(new Mobile("mi", 20000, 6, 4));
arr.add(new Mobile("realme", 15000, 4, 3));
arr.add(new Mobile("Samsung", 30000, 8, 5));
CompareLogic logic = new CompareLogic();
CompareRam ram = new CompareRam();
// Collections.sort(arr);
// System.out.println(arr);
Collections.sort(arr,logic);
System.out.println(arr);
// Collections.sort(arr, ram);
// System.out.println(arr);
}
}
Output:
//Default price sorting
[Samsung - 30000 - 8 - 5, mi - 20000 - 6 - 4, realme - 15000 - 4 - 3]
//Custom rating sorting
[realme - 15000 - 4 - 3, mi - 20000 - 6 - 4, Samsung - 30000 - 8 - 5]
//Custom ram sorting
[realme - 15000 - 4 - 3, mi - 20000 - 6 - 4, Samsung - 30000 - 8 - 5]
Top comments (0)