Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Map.Entry值对集合进行排序_Java_Sorting_Set - Fatal编程技术网

Java 使用Map.Entry值对集合进行排序

Java 使用Map.Entry值对集合进行排序,java,sorting,set,Java,Sorting,Set,我有一个集合如下: Set<Map.Entry<String,String>> set = new HashSet<>(); Set Set=newhashset(); 如何根据Map.Entry的键对该Set进行排序 谢谢。您不能对常规Java集进行排序,因为它没有排序。如果您想要一个有序的集合,一个选项是使用TreeSet。您可以使用自定义比较器创建TreeSet,然后将HashSet添加到其中: TreeSet<Map.Entry<Str

我有一个
集合
如下:

Set<Map.Entry<String,String>> set = new HashSet<>();
Set Set=newhashset();
如何根据
Map.Entry
的键对该
Set
进行排序


谢谢。

您不能对常规Java
集进行排序,因为它没有排序。如果您想要一个有序的集合,一个选项是使用
TreeSet
。您可以使用自定义比较器创建
TreeSet
,然后将
HashSet
添加到其中:

TreeSet<Map.Entry<String,String>> ts
    = new TreeSet<Map.Entry<String,String>>(new Comparator<Map.Entry<String,String>>() {
    @Override
    public int compare(Map.Entry<String,String> entry1, Map.Entry<String,String> entry2) {
        return entry1.getKey().compareTo(entry2.getKey());
    }
});

ts.addAll(set);

正如Tim所建议的,为此使用
TreeSet
。但是,您不需要定义自己的
比较器
实现,只需使用
映射中已经定义的
比较器
类,像这样实例化
树集即可

Set<Map.Entry<String, String>> set = new TreeSet<>(Map.Entry.comparingByKey());
Set Set=newtreeset(Map.Entry.comparingByKey());

这将为您提供一个有序的
集合

collections.sort行抛出编译时错误。我想不出来。
Set<Map.Entry<String, String>> set = new TreeSet<>(Map.Entry.comparingByKey());