简体   繁体   English

按升序和降序对数组的 LinkedHashmap 进行排序 - Java

[英]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?如何通过将数组中的第一个元素按降序排序,将第二个元素按升序排序,对 int 数组的 LinkedHashMap 进行排序?

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.其中 No. 是关键,Vol。 and Rank are the elements in the int array that the LinkedHashMap contains和 Rank 是 LinkedHashMap 包含的 int 数组中的元素

It doesn't make much sense to ask how to sort a Map .询问如何对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.这实质上是对映射条目进行流式处理,并根据通过 lambda 表达式提取的整数对它们进行排序。 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.我建议您不要在数组中存储不同的数据域(vol 和 rank)。 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.但是,除非您拥有数百万个对象或具有高事务量的应用程序,否则这通常不是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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