Reputation: 175
I want to iterate a list in a specify order using the Interface Iterator. In this case, I want to iterate the list (listofproducts) in descending product.prize order.
public class Invoice {
private static int static_id;
private int id;
private String date;
private List<Product> listofproduct = new ArrayList<Product>();
private boolean open;
}
public class Product {
private static int count = 0;
private int code;
private String name;
private String description;
private double price;
}
I have a public method to get the price. How can I solve this?
Upvotes: 2
Views: 948
Reputation: 2446
There are two way to achieve that. With Comparator it is easy to use, you should create a new implementation of the interface Comparator and then implement the compare and equals methods. It is really powerful because you can create several comparator to sort in different fields.
You can also make you Product as Comparable and then implements the compareTo method.
You can see sample with camparator and comparable interfaces
Upvotes: 0
Reputation: 397
You should use the Comparable<T>
interface to implement your comparaison logic :
class Product implements Comparable<Product>{
private static int count = 0;
private int code;
private String name;
private String description;
private Double price;
@Override
public int compareTo(Product p) {
return price.compareTo(p.getPrice());
}
}
Now to sort the list you can simply use :
Collections.sort(listOfProduct);
Upvotes: 2
Reputation: 4430
If the amount of data isn't too big you can do the following without thinking about the performace:
List<Product> sortList = new ArrayList<>(origList);
Collections.sort(sortList, new Comparator<Product>() {
@Override
public int compare(Product arg0, Product arg1) {
return (int)(arg1.getPrice() - arg0.getPrice());
}
});
This will create a copy of the original list which will be sorted by a comparator. After that, iterating over sortList
will be sorted by price
(descending)
Upvotes: 2