本文介绍了在字符串[]中存储排序后的hashmap的键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉发布这个不清楚的问题。这是我第一次使用hashmap,因此我感到困惑。试图在这里以更好的方式解释这个问题 -



我有一个基于值的排序hashmap。我想从有序映射中提取键并将它们存储在一个String []数组中。键的顺序(按值排序)很重要。
我用这段代码对值进行hashmap排序 -



为了提取关键数组,我尝试了

  String [] keys =(String [])(hm.keySet()。toArray(new String [hm.size()]))

(这里hm是散列表)

但是这种方法并不奏效。键字符串[]具有键,但不是按照我想要的排序顺序。






更新:
I使用linkedHashMap并能够将排序的键值存储在数组中。 是代码链接。

解决方案

根据拼写错误以及您使用hashmap的说明,密钥检索的顺序与插入顺序不一致。为此使用LinkedHashMap。这是使用你做外部排序,然后插入排序的条目到地图中。



如果要在条目被插入到映射时进行排序,请使用TreeMap 。您可以使用自定义比较器,也可以使您的关键对象实现Comparable接口。


I am sorry for posting this unclear question. This is my first time using hashmap and hence i was confused. Have tried to explain this question in a better way here - store key values of hashmap in string[]

I have a sorted hashmap based on values. I want to extract the keys from the sorted map and store them in a String[] array. The order of the keys(sorted by values) is important.I used this code to sort the hashmap on values - http://www.xinotes.org/notes/note/306/

To extract the key array, I tried

 String[] keys = (String[])( hm.keySet().toArray( new String[hm.size()] ) )

(here hm is the hashmap)

But this method didnt work. The keys string[] has the keys but not in the sorted order I want.


Update:I used linkedHashMap and was able to store the sorted key values in an array. Here is the link for the code.

解决方案

Based on the typo, and your clarification that you are using hashmap, the order of the keys retrieval will not be consistent with the insert order. Use LinkedHashMap for that. This is using you do external sorting and then insert sorted entries into the map.

If you want the entries to be sorted while they are being inserted into the Map, use TreeMap. You can either use a custom comparator or make your key object implement Comparable interface.

这篇关于在字符串[]中存储排序后的hashmap的键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:26