Is it possible to sort a List
interface with object of ArrayList()
?
List</*classname*/> list = new ArrayList<>();
I'm using application.properties
of Spring boot to set the value in List interface
ModuleNames.java
public class ModuleNames {
private String moduleId;
private String moduleName;
//getters & setters.
}
Controller
@RequestMapping(value = "/getModuleNames", method = { RequestMethod.GET })
public @ResponseBody List<String> getModuleNames() {
List<ModuleNames> moduleNamesList = new ArrayList<>();
moduleNamesList.add(new ModuleNames("Country", env.getProperty("bulkUpload.location.country")));
moduleNamesList.add(new ModuleNames("State", env.getProperty("bulkUpload.location.state")));
moduleNamesList.add(new ModuleNames("City", env.getProperty("bulkUpload.location.city")));
moduleNamesList.add(new ModuleNames("Area Pincode", env.getProperty("bulkUpload.location.areaPincode")));
return moduleNamesList;
does anybody know how to sort the list.
I've tried
moduleNamesList.sort(Comparator.naturalOrder());
Collections.sort(moduleNamesList);
but both doesn't seem to work. Please help me here
You can avoid defining the comparison logic by using an instance method reference and the Comparator.comparing method – which extracts and creates a Comparable based on that function.
We're going to use the getters to build the Lambda expression.
sort the list by moduleName:
moduleNamesList.sort(Comparator.comparing(ModuleNames::getModuleName));
sort the list by moduleName in reverse order:
moduleNamesList.sort(Comparator.comparing(ModuleNames::getModuleName).reversed());
sort the list by first moduleName and then moduleId:
moduleNamesList.sort(Comparator.comparing(ModuleNames::getModuleName).thenComparing(ModuleNames::getModuleId));
You can also use custom comparator:Use This Reference