简体   繁体   中英

How can I sort a list which is a class that has an attribute of id in id descending order?

I have a class Product, that has a OneToMany relationship with another class called Feedback. I am doing a PostMapping to retrieve that class from my database to present it in a web view. I am unable to figure out how to implement a comparator to sort my List fs in descending order. The code thus far is below:

@PostMapping("/view/{id}")
    public ModelAndView addReview(@PathVariable("id") int id, @RequestParam("review") String review, HttpServletRequest request) {
        Product product = dao.findById(id).get();
        Feedback feedback = new Feedback(review);
        product.getFeedbacks().add(feedback);
        feedback.setProduct(product);
        dao.save(product);
        List<Feedback> fs = product.getFeedbacks();
        HttpSession session = request.getSession();
        session.setAttribute("fs", fs);
        return new ModelAndView("/view").addObject("product", product);
    }

How can I sort my fs based on the id which is the primary key in descending order?

1.Add the interface comparable to your object.

Public class  Feedback implements Comparable<Feedback>

2 override compareTo method

@Override
public int compareTo(Feedback o) {
    return this.getId().compareTo(o.getId());
}
  1. Use collections to sort the list.

3.1Feedback ids in ascending order

Collections.sort(fs);

3.2 Feedback ids in reverse order

Collections.sort(fs, Collections.reverseOrder());

Try by making a FeedbackSorter

class FeedbackSorter implements Comparator<Feedback> 
{ 
    public int compare(Feedback a, Feedback b) 
    { 
        return a.getProduct().getID() - b.getProduct().getID()
    } 
} 

Then Collections.sort(fs, new FeedbackSorter ());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM