hashMap的定制排序
程序员文章站
2022-06-05 14:22:26
...
hashmap主要根据key值和value值的排序
一 建立hashMap
HashMap<String,String> map = new HashMap<>();
二 构建List 集合
List<Map.Entry<String,String>> list1 = new ArrayList<>(map.entryset());
三 运用Collections工具类中的sort方法,并使用comparator接口,推荐使用泛型
Collections.sor(list1,(s1,s2)->(s1.getKey().compareTo(s2.getKey());
输出的话,for (MapEntry<String,Integer> entry:list1)
package day07.src.com.atguigu.java;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HashSortTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String , Integer> map = new HashMap<>();
map.put("a",2);
map.put("d",1);
map.put("b",3);
map.put("c",1);
for(Map.Entry<String, Integer> entry:map.entrySet()){
System.out.println(entry.getKey()+" "+ entry.getValue());
}
System.out.println("---------1升序排序-----------");
//1. 不用泛型表达式 ,根据key值排序
List<Map.Entry<String,Integer>> list1 = new ArrayList<>(map.entrySet());
Collections.sort(list1,new Comparator<Map.Entry<String,Integer>>(){
@Override
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
// TODO Auto-generated method stub
return o1.getKey().compareTo(o2.getKey());
}
});
for(Map.Entry<String,Integer> entry:list1){
System.out.println(entry.getKey()+" "+entry.getValue());
}
System.out.println("----------2降序排序--------");
//2用泛型表达式 , 根据key值排序
List<Map.Entry<String,Integer>> list2 = new ArrayList<>(map.entrySet());
Collections.sort(list2,(s1,s2)->
s2.getKey().compareTo(s1.getKey())
);
for(Map.Entry<String, Integer> entry: list2){
System.out.println(entry.getKey()+" "+entry.getValue());
}
System.out.println("_________3升序排序___________");
//3.根据value值排序 不用泛型表达式
List<Map.Entry<String,Integer>> list3 = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
Collections.sort(list3, new Comparator<Map.Entry<String, Integer>>(){
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
// TODO Auto-generated method stub
return o1.getValue().compareTo(o2.getValue());
}
});
for(int i=0;i<list2.size();i++){
System.out.println(list2.get(i).getKey()+" "+list2.get(i).getValue());
}
System.out.println("-------------------4降序排序----------------");
//4根据value值排序,泛型表达式
List<Map.Entry<String,Integer>> list4 = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
Collections.sort(list4, (s3,s4)->(s4.getValue().compareTo(s3.getValue())));
for(Map.Entry<String, Integer> entry:list4){
System.out.println(entry.getKey()+" "+ entry.getValue());
}
}
}