【问题标题】:Telling HashSet how to sort the data告诉 HashSet 如何对数据进行排序
【发布时间】:2012-10-29 20:47:42
【问题描述】:

我正在尝试创建一个 HashSet(或任何集合类型 - 但我认为 HashSet 最适合我),无论插入什么,它都会保持有序。这是我正在处理的一个联系人管理器项目。 我一直在试验,下面的例子。

import java.util.*;

public class TestDriver{

    public static void main(String[] args)
    {
        FullName person1 = new FullName("Stephen", "Harper");
        FullName person2 = new FullName("Jason", "Kenney");
        FullName person3 = new FullName("Peter", "MacKay");
        FullName person4 = new FullName("Rona", "Ambrose");
        FullName person5 = new FullName("Rona", "Aabrose");


        HashSet<FullName> names = new HashSet<FullName>();

        names.add(person3);
        names.add(person1);
        names.add(person4);
        names.add(person2);

        System.out.println(names);      
   } 
}

我希望输出按字母顺序排列姓名 - 至少按照他们的名字或姓氏。但是,我什至无法辨别 HashSet 用来得出此排序的方法;

[Jason Kenney, Rona Ambrose, Stephen Harper, Peter MacKay]

我的问题是,我如何告诉我的程序如何根据我的规范对名称进行排序?

【问题讨论】:

  • 对 HashSet 进行排序在术语上是矛盾的。您正在寻找的是SortedSet 的任何实现,例如TreeSet

标签: java hashset


【解决方案1】:

HashSet 没有为条目提供任何有意义的顺序。 documentation 说:

它不保证集合的迭代顺序;在 特别是,它不保证订单将保持不变 随着时间的推移。

要获得合理的排序,您需要使用不同的 Set 实现,例如 TreeSetConcurrentSkipListSetSortedSet 接口的这些实现允许您提供一个 Comparator 来指定如何对条目进行排序;类似:

public class SortByLastName implements Comparator<FullName>{
    public int compare(FullName n1, FullName n2) {
        return n1.getLastName().compareTo(n2.getLastName());
    }
}

TreeSet<FullName> names = new TreeSet<FullName>(new SortByLastName());

您可以改为让 FullName 类实现 Comparable 接口,但如果您想有时按姓氏、有时按名字或其他条件排序,这可能无济于事。

【讨论】:

    【解决方案2】:

    使用Treeset 进行自然排序。

    HashSet--- not ordered/sorted
    LinkedhashSet--- maintains insertion order
    TreeSet--- sorts in natural order
    

    对于您的情况,请改用 TreeSet。

    【讨论】:

      【解决方案3】:

      HashSet 不保持顺序,去TreeSet 并实现你自己的Comparator 来指导TreeSet 如何比较

      new TreeSet<FullName>(new Comparator<FullName>(){
              public int compare(Fullname one, FullName two{/*logic*/}
      });
      

      【讨论】:

        【解决方案4】:

        似乎您需要TreeSet 来实现字母顺序或LinkedHashSet 来保持插入顺序。

        请注意,您的 FullName 必须实现 Comparable&lt;FullName&gt; 才能在 TreeSet 中使用(或者您必须提供外部 Comparator`)。

        【讨论】:

          【解决方案5】:

          试试这个:

           System.out.println(names.toList.sorted)
          

          【讨论】:

          • 不,我正在运行 scala。
          猜你喜欢
          • 2014-04-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多