Telling HashSet how to sort the data

夙愿已清 提交于 2019-11-28 11:28:23

HashSet does not provide any meaningful order to the entries. The documentation says:

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

To get a sensible ordering, you need to use a different Set implementation such as TreeSet or ConcurrentSkipListSet. These implementations of the SortedSet interface let you provide a Comparator that specifies how to order the entries; something like:

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());

You could instead make the FullName class implement the Comparable interface, but this might be unhelpful if you wanted to sometimes sort by last name, sometimes by first name, or other criteria.

use Treeset for natural ordering.

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

for your case use TreeSet instead.

HashSet doesn't preserve order, Go for TreeSet and implement your own Comparator to instruct TreeSet how to compare

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

See

Seems like you need TreeSet to achieve alphabetical order or LinkedHashSet to preserve insertion order.

Note that your FullName must implement Comparable<FullName> in order to be used in TreeSet (or you have to provide external Comparator`).

Try this:

 System.out.println(names.toList.sorted)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!