Java – data structure with key value mapping and sorting

I need a data structure that provides key value mapping, such as map, but this also allows me to obtain keys based on (int) indexes (e.g. MyKey = MYDS. Get (index)) without iterating the data structure to obtain the keys of the required indexes

I thought about using LinkedHashMap, but I didn't see a way to get the key at a given index What did I miss in LinkedHashMap? Or can I use another data structure?

Editor: This is not repeated The correct answer to another question is to use some sort map; However, this is not the correct answer to this question, because I want to be able to retrieve an entry from the data structure through integer index, which is not supported in any Java library

Solution

LinkedHashMap provides hash table / bidirectional linked list implementation of map interface Because it extends HashMap, it is still supported by arrays, but there is also a list of two-way linked entry objects to ensure that the iteration order is predictable

So, basically, it means that when you iterate through the map:

for (Map.Entry<keyType,valueType>> entry : linkedHashMap.entrySet())
{
   System.out.println("Key: " + entry.getKey().toString() + 
                     " Value: " + entry.getValue.toString());
}

It will print in the order you add keys, not in the unlinked map. It will not print in the insertion order You cannot access the elements of an array as you would like, because arrays that support hashing are not ordered Only the two - way linked list was ordered

Solution:

You are looking for a linkedmap from Apache Commons

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
分享
二维码
< <上一篇
下一篇>>