Android sorts the instances of map by key and value respectively

1、 Theoretical preparation

Map is the collection interface of key value pairs. Its implementation classes mainly include HashMap, treemap, hashtable and LinkedHashMap.

Treemap: the implementation of navigablemap based on red black tree. The map is sorted according to the natural order of its keys, or according to the comparator provided when creating the map, depending on the construction method used.

The values of HashMap have no order. It is implemented according to the hashcode of key. How do we sort this unordered HashMap? Sort by referring to the value of treemap.

Map.entry returns the collections view.

2、 Key sort

Treemap is in ascending order by default. If we need to change the sorting method, we need to use the comparator. Comparator is a comparator interface that can sort collection objects or arrays. The public compare (t O1, to2) method that implements this interface can realize sorting, as follows:

The operation results are as follows:

3、 Value sort

The above example sorts according to the key value of treemap, but sometimes we need to sort according to the value of treemap. To sort values, we need to use the sort (list < T > list, comparator <? Super T > C) method of collections, which sorts the specified list according to the order generated by the specified comparator. However, there is a precondition that all elements must be able to be compared according to the provided comparator, as follows:

The operation results are as follows:

The above is all the contents of the example of Android sorting map by key and value brought by Xiaobian. I hope you can 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
分享
二维码
< <上一篇
下一篇>>