On sorting in Java collection

Here we discuss the sorting of list, set and map, including sorting according to the value of map.

1) List sort

List sorting can directly use the sort method of collections or the sort method of arrays. In the final analysis, collections is to call the sort method of arrays.

If it is a custom object, we need to implement the comparable interface so that the object itself has the function of "comparison". Of course, we can also use the comparator externally to specify its sorting.

For example:

Sort:

Of course, you can go directly to collections Sort (US). Here, the comparator is used to optimize the user's own comparison method CompareTo (sort people of the same age according to the user name and string).

Briefly, arrays uses insert sort and merge sort. When the array length is small, insert sort directly.

2) Set sort

Set includes HashSet and TreeSet. HashSet is based on HashMap and TreeSet is based on treemap.

Treemap is implemented with red and black trees, and naturally has sorting function. "Naturally has sorting function" means that it has ascending and descending iterators.

So how do hashsets sort? We can convert the HashSet into a list, and then sort it with a list.

For example:

You can also convert a HashSet into an array and sort it with arrays.

3) Map sorting

Map includes HashMap and treemap. As mentioned above, treemap is implemented with red black tree and naturally has sorting function.

How can HashMap be sorted by "key"? The method is very simple. Use HashMap to construct a treemap.

How to sort by "value"?

Put forward the entry of map into set structure, then turn set into list, and finally sort according to list.

The above discussion on the sorting problem in Java collection is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>