猿问

如何对应用程序属性值进行排序

是否可以对List带有对象的接口进行排序ArrayList()?


List</*classname*/> list = new ArrayList<>();


我正在使用application.propertiesSpring boot 设置 List 界面中的值


ModuleNames.java


public class ModuleNames {


    private String moduleId;

    private String moduleName;


    //getters & setters.

}

控制器


@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;

有谁知道如何对列表进行排序。

我试过了

  1. moduleNamesList.sort(Comparator.naturalOrder());

  2. Collections.sort(moduleNamesList);

但两者似乎都不起作用。请在这里帮助我


慕姐4208626
浏览 104回答 3
3回答

PIPIONE

您需要为 ModuleNames 对象编写自定义比较器,因为 Java 不知道如何对其进行排序,因为它不是原始类型。例如:Collections.sort(moduleNamesList, new Comparator<ModuleNames>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public int compare(ModuleNames o1, ModuleNames o2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return o1.getModuleId().compareTo(o2.getModuleId());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });或者moduleNamesList.sort(new Comparator<ModuleNames>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public int compare(ModuleNames o1, ModuleNames o2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return o1.getModuleName().compareTo(o2.getModuleName());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });

绝地无双

您可以通过使用实例方法引用和 Comparator.comparing 方法来避免定义比较逻辑 - 该方法根据该函数提取并创建一个 Comparable。我们将使用 getter 来构建 Lambda 表达式。按模块名称对列表进行排序:moduleNamesList.sort(Comparator.comparing(ModuleNames::getModuleName));按模块名称倒序对列表进行排序:moduleNamesList.sort(Comparator.comparing(ModuleNames::getModuleName).reversed());首先按 moduleName 对列表进行排序,然后按 moduleId 对列表进行排序:moduleNamesList.sort(Comparator.comparing(ModuleNames::getModuleName).thenComparing(ModuleNames::getModuleId));

斯蒂芬大帝

moduleNamesList.sort(Comparator.comparing(ModuleNames::getName)); moduleNamesList.sort(Comparator.comparing(mn&nbsp;->&nbsp;mn.name));或者甚至更排序:moduleNamesList.sort(Comparator.comparing(ModuleNames::getName) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.thenComparing(ModuleNames::getId));
随时随地看视频慕课网APP

相关分类

Java
我要回答