Questions about sorting HashSet in java

Source: Internet
Author: User

The following two methods are described:

Method 1: convert the HashSet to List and use Collections. sort () for sorting.
Method 2: convert a Hashset to a TreeSet

The following code provides two methods:

The code is as follows: Copy code

Public class HashSetSortingDemo {
Public static void main (String args []) {
HashSet <String> names = new HashSet <String> ();
Names. add ("Asker ");
Names. add ("Crak ");
Names. add ("Bayliss ");
Names. add ("Mohna ");
Names. add ("Dina ");
System. out. println ("HashSet before sorting:" + names );
// Convert the HashSet to List and use Collections. sort () for sorting
List <String> tempList = new ArrayList <String> (names );
Collections. sort (tempList );
System. out. println ("HashSet element in sorted order:" + tempList );
// Use TreeSet to sort HashSet
TreeSet <String> sorted = new TreeSet <String> (names );
System. out. println ("HashSet sorted using TreeSet:" + sorted );
    }
}

There is just a problem. Since we want to sort data, why didn't we need to sort hashset?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.