<div id="article_content" class="article_content">
HashMap排序
1、按照key排序
对于java中Map的排序,有排序Map,比如TreeMap,对于这个Map,首先只能按照键排序,其次再put和remove的时候由于需要排序,性能上会有所牺牲。
这种方案,使用
hashmap进行创建和添加,如果需要按照key排序,则可以将该hashmap作为参数传递到new TreeMap(hashmap),则可以完成按照key的排序:
<div class="dp-highlighter">
<p class="java" style="display: none;" title="java Map排序(按key和按value)">TreeMap treemap = new TreeMap(hashmap);
?
2、按照value排序
使用hashmap,然后添加比较器,进行排序
?? Map<String,?Integer>?keyfreqs?=?<span class="keyword">
<span style="color: #7f0055;">new</span></span>?HashMap<String,?Integer>();???
?? ArrayList<Entry<String,Integer>>?l?=?<span class="keyword">
<span style="color: #7f0055;">new</span></span>?ArrayList<Entry<String,Integer>>(keyfreqs.entrySet());?? ??
?? Collections.sort(l,?<span class="keyword">
<span style="color: #7f0055;">new</span></span>?Comparator<Map.Entry<String,?Integer>>()?{?? ??
<span class="keyword"><span style="color: #7f0055;"><span style="color: #000000;">?? </span>
public</span></span>?<span class="keyword">
<span style="color: #7f0055;">int</span></span>?compare(Map.Entry<String,?Integer>?o1,?Map.Entry<String,?Integer>?o2)?{?? ??
<span class="keyword"><span style="color: #7f0055;"><span style="color: #000000;">??????????????? </span>
return</span></span>?(o2.getValue()?-?o1.getValue());?????}?????}); ??
<span class="keyword">
<span style="color: #7f0055;">?? </span></span>
<span class="keyword">
<span style="color: #7f0055;">?? for</span></span>(Entry<String,Integer>?e?:?l)?{ ??
?????? System.out.println(e.getKey()?+?<span class="string"><span style="color: #0000ff;">"::::"</span></span>?+?e.getValue()); ??
????? }??
?
HashMap遍历
在java中使用HashMap是主要有两种遍历方法,代码如下:
第一种:
<p class="alt">Iterator?iterator?=?hashmap.keySet().iterator();
<p class="alt">???? Object?value?=?hashmap.get(iterator.next());
<p class="alt">?
<span>第二种:</span>
<span><span>HashMap?hashmap?=?</span><span class="keyword">new</span><span>?HashMap();</span> </span>
<span><span>Iterator?iterator?=?hashmap.entrySet().iterator();???????????</span> </span>
<span><span class="keyword">while</span><span>?(iterator?.hasNext())?{</span> </span>
<span><span>??? Entry?entry?=?(Entry)?iterator?.next();</span> </span>
<span>??? <span>Object?value=?entry.getValue();</span> </span>
<span>??? <span>Object?key?=entry.getKey();</span> </span>
<span><span>?? }</span></span>