如何根据值对地图进行排序

时间:2013-09-06 20:35:12

标签: java sorting map

我正在尝试将捆绑包名称及其最新版本存储在地图中。

下面是我的newDirs ArrayList<Map<String, String>>(),我应该从中获取Bundle名称及其最新版本 -

[{objectName=/storage/Model/Framework/1.0.0/, objectId=4fa042a5a56c861104fa05c246cf850522a2354ca223, objectType=DIRECTORY}, 
{objectName=/storage/Model/Framework/1.0.1/, objectId=4fa042a5a66c860d04fa056bbe1cf50522a14094ca3f, objectType=DIRECTORY}]

现在从上面的List中,我应该提取最新版本的Framework bundle。所以在上面的例子中,它是1.0.1 version,包名称是Framework。因此,我的地图会将Framework作为密钥存储,1.0.1作为上述情况下捆绑的版本。

以下是我的代码 -

final List<Map<String, String>> newDirs = new ArrayList<Map<String, String>>();

for(String ss : list) {

    //some code here for newDirs

    Map<String, String> map = storageDirectorySort(newDirs);
    System.out.println(map);
}

/**
 * Sort the list and then return the map as the Bundle Name and its Latest version
 *
 */
private static Map<String, String> storageDirectorySort(List<Map<String, String>> newDirs) {

    Map<String, String> map = new LinkedHashMap<String, String>();

    // do the sorting here and always give back the latest version of the bundle and its name

    return map;
}

任何人都可以帮助我。我不确定这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

您需要另一个辅助方法来帮助解析版本号。然后在storageDirectorySort方法中调用它:

    private static int getVersion(Map<String, String> dir) {
        String objectName = dir.get("objectName");
    // Get the various parts of the name
        String[] nameParts = objectName.split("/");
    // Get the version from the nameParts
        String[] versionString = nameParts[nameParts.length - 1].split("\\.");
        // Parse version String into an int
        return (Integer.valueOf(versionString[0]) * 1000000)
                + (Integer.valueOf(versionString[1]) * 10000)
                + (Integer.valueOf(versionString[2]) * 100);
    }

    private static Map<String, String> storageDirectorySort(
            List<Map<String, String>> newDirs) {

        Map<String, String> latestVersion = null;
        for (Map<String, String> bundle : newDirs) {
            int version = getVersion(bundle);
            if (latestVersion == null || version > getVersion(latestVersion)) {
                latestVersion = bundle;
            }
        }

        return latestVersion;
    }

注意:此代码中没有异常处理,我建议添加一些。除此之外,我已对其进行测试以验证其是否有效。