Java 哈希集的降序排序

Java 哈希集的降序排序,java,sorting,Java,Sorting,我想根据哈希集中字符串的长度对哈希集值进行降序排序 HashSet<String> hs = new HashSet<String>(); hs.add("The World Tourism Organization"); hs.add("reports the following ten countries"); hs.add("as the most visited in terms of the number"); hs.add("of international

我想根据哈希集中字符串的长度对哈希集值进行降序排序

HashSet<String> hs = new HashSet<String>();
hs.add("The World Tourism Organization");
hs.add("reports the following ten countries");
hs.add("as the most visited in terms of the number");
hs.add("of international travellers.");
System.out.println(hs);

按降序排序的方法是什么?

按定义排序的哈希集不会对其成员进行排序。你想要的是一棵树

如果有哈希集,只要对象具有可比性,就可以从中创建树集:

树集ts=新树集(hs)


HashSet按定义不排序其成员。你想要的是一棵树

如果有哈希集,只要对象具有可比性,就可以从中创建树集:

树集ts=新树集(hs)


您需要使用
TreeSet
而不是
HashSet
和您自己的自定义比较器,该比较器将根据值的长度对值进行排序

Set<String> yourSet = new TreeSet<>(new Comparator<String>() {
    public int compare(String o1, String o2) {
        // Your comparison logic goes here
        return 0;
    }
});

// Add all the HashSet values to the TreeSet
yourSet.addAll(hs);
Set yourSet=新树集(新比较器(){
公共整数比较(字符串o1、字符串o2){
//你的比较逻辑是这样的
返回0;
}
});
//将所有HashSet值添加到树集
yourSet.addAll(hs);

您需要使用
树集,而不是带有自定义比较器的
哈希集
,该比较器将根据值的长度对值进行排序

Set<String> yourSet = new TreeSet<>(new Comparator<String>() {
    public int compare(String o1, String o2) {
        // Your comparison logic goes here
        return 0;
    }
});

// Add all the HashSet values to the TreeSet
yourSet.addAll(hs);
Set yourSet=新树集(新比较器(){
公共整数比较(字符串o1、字符串o2){
//你的比较逻辑是这样的
返回0;
}
});
//将所有HashSet值添加到树集
yourSet.addAll(hs);

您应该使用TreeSet而不是hashset,或者创建一个比较器来对集合进行排序

您应该使用TreeSet而不是hashset,或者创建一个比较器来对集合进行排序

hashset
没有为条目提供任何有意义的顺序。文件说:

它不保证集合的迭代顺序;特别是,它不能保证订单在一段时间内保持不变

要获得合理的排序,您需要使用不同的集合实现,例如
TreeSet
TreeSet
允许您提供一个
比较器
,指定如何对条目排序;比如:

public class SortByString implements Comparator<FullName>{
    public int compare(FullName n1, FullName n2) {
        return n1.getLastName().compareTo(n2.getLastName());
    }
}
公共类SortByString实现了Comparator{
公共整数比较(全名n1,全名n2){
返回n1.getLastName().compareTo(n2.getLastName());
}
}

哈希集
不为条目提供任何有意义的顺序。文件说:

它不保证集合的迭代顺序;特别是,它不能保证订单在一段时间内保持不变

要获得合理的排序,您需要使用不同的集合实现,例如
TreeSet
TreeSet
允许您提供一个
比较器
,指定如何对条目排序;比如:

public class SortByString implements Comparator<FullName>{
    public int compare(FullName n1, FullName n2) {
        return n1.getLastName().compareTo(n2.getLastName());
    }
}
公共类SortByString实现了Comparator{
公共整数比较(全名n1,全名n2){
返回n1.getLastName().compareTo(n2.getLastName());
}
}