按名称排序HashMap <string [],boolean =“”>,它以String []的形式按升序排列

时间:2018-01-07 06:51:49

标签: java sorting hashmap

我想对HashMap进行排序&lt; String [],Boolean&gt;按升序排列。它可以正常使用我编写的代码

//HashMap<String[], Boolean> literalTable = new HashMap<>(); // declared some where in my code
ArrayList<String[]> arrayList = new ArrayList<>();
    for (int i = 0; i < literalTable.size(); ++i){
        String[] str = {};
        arrayList.add(str);
    }
    for (Map.Entry m: literalTable.entrySet()){
        String[] str = (String[]) m.getKey();
        Integer index = Integer.parseInt(str[0]);
        arrayList.set(index, str);
    }

    arrayList.sort(Comparator.comparing(p -> p[0]));

我的问题是,有没有办法完成同样的任务? 我用Google搜索并找到了一个解决方案,它说你可以使用TreeMap,但它不能正常工作。

1 个答案:

答案 0 :(得分:1)

您需要将比较器传递给TreeMap构造函数以对数组字符串

进行排序
Map<String[], Boolean> hashMap = new HashMap<String[], Boolean>();
hashMap.put(new String[]{"bfa", "asdfs", "gr"}, true);
hashMap.put(new String[]{"efd", "asdfs", "gr"}, true);
hashMap.put(new String[]{"asd", "asdfs", "gr"}, true);
hashMap.put(new String[]{"bfd", "asdfs", "gr"}, true);

TreeMap<String[], Boolean> treeMap = new TreeMap<>(Comparator.comparing(a -> a[0]));
treeMap.putAll(hashMap);
treeMap.forEach((k, v) -> System.out.println(Arrays.toString(k) + " " + v));

输出

[asd, asdfs, gr] true
[bfa, asdfs, gr] true
[bfd, asdfs, gr] true
[efd, asdfs, gr] true

您可以尝试按键数组中的第一个元素进行排序,并使用LinkedHashMap来维护订单

        LinkedHashMap<String[], Boolean> orderedMap = hashMap.keySet().stream()
                .sorted(Comparator.comparing(a -> a[0])) // ignore case if required
                .collect(Collectors.toMap(a -> a, a -> hashMap.get(a), (a, b) -> a, LinkedHashMap::new));
        orderedMap.forEach((k, v) -> System.out.println(Arrays.toString(k) + " " + v));

输出

[asd, asdfs, gr] true
[bfa, asdfs, gr] true
[bfd, asdfs, gr] true
[efd, asdfs, gr] true

如果您需要按下一个元素排序,如果第一个元素匹配,则可以将数组连接到字符串并进行排序

LinkedHashMap<String[], Boolean> orderedMap = hashMap.keySet().stream()
                .sorted(Comparator.comparing(a -> Arrays.toString(a))) // ignore case if required
                .collect(Collectors.toMap(a -> a, a -> hashMap.get(a), (a, b) -> a, LinkedHashMap::new));