告诉HashSet如何对数据进行排序

我正在尝试创建一个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 names = new HashSet(); 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不为条目提供任何有意义的顺序。 文件说:

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

要获得合理的排序,您需要使用不同的Set实现,例如TreeSet或ConcurrentSkipListSet 。 SortedSet接口的这些实现允许您提供指定如何对条目进行排序的Comparator ; 就像是:

 public class SortByLastName implements Comparator{ public int compare(FullName n1, FullName n2) { return n1.getLastName().compareTo(n2.getLastName()); } } TreeSet names = new TreeSet(new SortByLastName()); 

您可以改为使FullName类实现Comparable接口,但如果您希望有时按姓氏排序,有时按名字或其他条件排序,则可能无效。

使用Treeset进行自然排序。

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

对于您的情况使用TreeSet而不是。

HashSet不保留顺序,Go for TreeSet并实现自己的Comparator来指示TreeSet如何比较

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

看到

  • API文件

好像你需要TreeSet来实现字母顺序或者LinkedHashSet来保持插入顺序。

请注意,您的FullName必须实现Comparable才能在TreeSet (或者您必须提供外部Comparator`)。

尝试这个:

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