-1

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?

e.g.

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

  • 1
    Create a class Track, containing 3 fields: number, volume, rank. Transform your Map into a Map (if you really need this map). Extract the values of the map and store them in a List. Sort the List by volume. Display the sorted List. – JB Nizet Nov 24 '15 at 17:39
  • 2
    Welcome to SO. Please take a look at [ask], and show us your work! – Martin Serrano Nov 24 '15 at 17:41
  • you cannot put 4 ,2 and 4, 1 in the map, map can not have same key twice – Kalpesh Soni Nov 25 '15 at 02:54

1 Answers1

0

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.

sprinter
  • 27,148
  • 6
  • 47
  • 78