Sort Custom Object in Java

Mi Guoliang
  1. Define a custom POJO, like this:

     package com.example.models;
    
     public class ManufacturerPrice {
    
         private String name;
    
         private String description;
    
         // ... ommit setters & getters
     }
    
  2. Define a Comparator variable, like this:

     Comparator<ManufacturerPrice> priceComparator =
                 (a, b) -> a.getName().compareTo(b.getName());
    
  3. Use Collections.sort with your custom Comparator, like this:

     // entities is a Collection of ManufacturerPrice, such as List, Set, etc.
     Collections.sort(entities, priceComparator);
    

If you like my share, you can:

• Follow My Programming Experiences Page on Facebook.

• Follow My Twitter.

• Subscribe to my mail list.