Java Map 按Key排序实例代码
JavaMap按Key排序
有时候我们业务上需要对map里面的值按照key的大小来进行排序的时候我们就可以利用如下方法来进行排序了,
packagetest; importjava.util.ArrayList; importjava.util.Collections; importjava.util.Comparator; importjava.util.HashMap; importjava.util.Iterator; importjava.util.List; importjava.util.Set; importjava.util.TreeSet; publicclassDemo{ privateHashMap<Integer,Object>map=newHashMap<Integer,Object>(); privateSet<Integer>keySet=map.keySet(); publicObjectget(Integerkey){ returnmap.get(key); } publicvoidput(Integerkey,Objectvalue){ map.put(key,value); } @SuppressWarnings("unchecked") publicvoidsort(){ List<Integer>list=newArrayList<Integer>(map.keySet()); Collections.sort(list,newComparator<Object>(){ publicintcompare(Objecta,Objectb){ returna.toString().toLowerCase().compareTo(b.toString().toLowerCase()); } }); this.keySet=newTreeSet<Integer>(list); } publicSet<Integer>keySet(){ returnthis.key } publicstaticvoidmain(String[]args){ Demomap=newDemo(); map.put(11,"加"); map.put(12,"关"); map.put(13,"注"); map.put(10,"添"); map.put(1,"小"); map.put(8,"记"); map.put(9,"得"); map.put(7,"客"); map.put(5,"的"); map.put(6,"博"); map.put(4,"豆"); map.put(3,"糖"); map.put(2,"小"); System.out.println("排序前"); for(Iteratorit=map.keySet().iterator();it.hasNext();){ Integerkey=(Integer)it.next(); System.out.println("key["+key+"],value["+map.get(key)+"]"); } // System.out.println("排序后"); System.out.println("\n"); map.sort(); for(Iteratorit=map.keySet().iterator();it.hasNext();){ Integerkey=(Integer)it.next(); System.out.println("key["+key+"],value["+map.get(key)+"]"); } } }
运行效果如下
排序前 key[1],value[小] key[2],value[小] key[3],value[糖] key[4],value[豆] key[5],value[的] key[6],value[博] key[7],value[客] key[8],value[记] key[9],value[得] key[10],value[添] key[11],value[加] key[12],value[关] key[13],value[注]
排序后 key[1],value[小] key[2],value[小] key[3],value[糖] key[4],value[豆] key[5],value[的] key[6],value[博] key[7],value[客] key[8],value[记] key[9],value[得] key[10],value[添] key[11],value[加] key[12],value[关] key[13],value[注]
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!