首页 > 代码库 > HashMap的遍历和排序

HashMap的遍历和排序

1.HashMap的遍历

package com.sheepmu;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class KMPText 
{
	public static void main(String[] args)
	{
		 Map<String,String> map=new HashMap<String,String>();
		 map.put("key1", "bb");
		 map.put("key0", "aaa");	
		 map.put("key3", "dddd");	 
		 map.put("key2", "cccccccc");
		 
		 //遍历方法0                  我个人最喜欢的遍历。集合的遍历还是用for-each的遍历是最爽滴~
		 for(Map.Entry<String, String> entry:map.entrySet())//值和value都需要遍历时
		 {
			 String key= entry.getKey().toString();
			 String value=http://www.mamicode.com/entry.getValue().toString();"white-space:pre">	 System.out.println("entry--->"+entry);
// 			 System.out.println("key---->"+key+"    value---->"+value+"   ");
		 }
		 
		  
		 //遍历方法1                       此方法效率也很高
		 Iterator it=map.entrySet().iterator();
		 while(it.hasNext())
		 {
			 Map.Entry entry=(Map.Entry) it.next();
			 String key= entry.getKey().toString();
			 String value=http://www.mamicode.com/entry.getValue().toString();>

2.HashMap的排序

 (1).方法:把map的entry取出来放到list里面,这样就相当于排list

          eg:对上面例子的HashMap按key从小到大排orvalue从长到短排

package com.sheepmu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class KMPText 
{
	public static void main(String[] args)
	{
		 Map<String,String> map=new HashMap<String,String>();
		 map.put("key1", "bb");
		 map.put("key0", "aaa");	
		 map.put("key3", "dddd");	 
		 map.put("key2", "cccccccc");
		 
		 //遍历 hashmap
		 for(Map.Entry<String, String> entry:map.entrySet()) 
		 {
			 String key= entry.getKey().toString();
			 String value=http://www.mamicode.com/entry.getValue().toString();>



注:如果希望遍历后的顺序与put进去的顺序一致,则采用LinkendHashMap

package com.sheepmu;
 
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class KMPText 
{
	public static void main(String[] args)
	{
		 Map<String,String> map=new HashMap<String,String>();
		 map.put("key1", "bb");
		 map.put("key0", "aaa");	
		 map.put("key3", "dddd");	 
		 map.put("key2", "cccccccc");
		 System.out.println("hashmap--->"+map); 
		 
		 Map<String,String> lmap=new LinkedHashMap<String,String>();
		 lmap.put("key1", "bb");
		 lmap.put("key0", "aaa");	
		 lmap.put("key3", "dddd");	 
		 lmap.put("key2", "cccccccc");
		 System.out.println("linkedhashmap--->"+lmap); 
		 		 
	}
	
}