简体   繁体   中英

Sort LinkedHashmap of Array in ascending and descending order - Java

How do I sort a LinkedHashMap of int arrays, by having the first element in the array sorted in descending order, and the second element sorted in ascending order?

eg

No.   Vol.  Rank     becomes      No.   Vol.  Rank      
1     4     2                     3     5     1
2     4     1                     1     4     2
3     5     1                     2     4     1
4     2     5                     4     2     5

where No. is the key and Vol. and Rank are the elements in the int array that the LinkedHashMap contains

It doesn't make much sense to ask how to sort a Map . What does make sense is asking how to present the data in a map in a certain order.

Assuming your data is organised as follows:

Map<Integer,int[]> data;

You can retrieve the entries in any order you want using the following:

data.entrySet().stream()
    .sorted(Map.Entry.comparingByValue(Comparator.comparingInt(a -> a[0])))
    ...

This essentially streams the map entries and sorts them according to the integers extracted via the lambda expression. What you do with the data depends on your needs but you could filter, collect to a list of entries or list of keys etc.

As a final point, this is not a great data structure. I suggest you not store different domains of data (vol and rank) in an array. Better to create a class and then store the data as a list of objects. You can create secondary maps to provide quick access if required. However this is generally not necessary unless you have millions of objects or have a high transaction volume application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM