java中map的排序问题
来源:互联网 发布:韩国语常用语网络 编辑:程序博客网 时间:2024/06/04 19:22
java中Map排序问题
按key排序
public class MapSortDemo { public static void main(String[] args) { Map<String, String> map = new TreeMap<String, String>(); map.put("KFC", "kfc"); map.put("WNBA", "wnba"); map.put("NBA", "nba"); map.put("CBA", "cba"); Map<String, String> resultMap = sortMapByKey(map); for (Map.Entry<String, String> entry : resultMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } public static Map<String, String> sortMapByKey(Map<String, String> map) { if (map == null || map.isEmpty()) { return null; } Map<String, String> sortMap = new TreeMap<String, String>( new MapKeyComparator()); sortMap.putAll(map); return sortMap; }}class MapKeyComparator implements Comparator<String>{ @Override public int compare(String str1, String str2) { return str1.compareTo(str2); }}
按value排序
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ Map<Character, Integer> map = new LinkedHashMap<>(); String sentence = sc.nextLine(); char[] arr = sentence.toCharArray(); for(int i=0;i<arr.length;i++){ if((arr[i] >= 'A' && arr[i] <= 'Z') || (arr[i] >='a' && arr[i] <= 'z')|| arr[i] >= '1' && arr[i] <= '9' || arr[i]==' '){ if(map.get(arr[i]) != null){ map.put(arr[i], map.get(arr[i])+1); }else{ map.put(arr[i], 1); } } } // 转化为list List<Map.Entry<Character, Integer>> entryList = new ArrayList<Map.Entry<Character, Integer>>( map.entrySet()); // public static <T> void sort(List<T> list, Comparator<? super T> c) Collections.sort(entryList, new MapValueComparator()); for (Map.Entry<Character, Integer> cc : entryList) { System.out.print(cc.getKey()); } } } private static class MapValueComparator implements Comparator<Map.Entry<Character, Integer>>{ @Override public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) { if(o1.getValue() < o2.getValue()) return 1; else if(o1.getValue() == o2.getValue()) return o1.getKey()-(o2.getKey()); else return -1; } }}
0 0
- java中map的排序问题
- java map 排序的问题
- Java中Map.keySet()返回值遍历的排序问题
- Java中Map的排序
- 关于java中Map排序问题
- Java中Map的问题
- java中map排序
- Java中Map排序
- java中map排序
- java对map中value的排序
- Java中Map的自定义排序
- Java中对Map的排序时间
- java中array,list,map的排序
- java中array,list,map的排序
- Java Map的排序
- 关于map中含数字string的排序问题
- 关于Map类型中对value进行排序的问题
- 关于map中含数字string的排序问题
- ueditor 添加支持文件存储到文件服务器
- C#中的invoke方法
- JAVA FileOutputStream写文件覆盖问题
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- 项目经理成长日记(一)——谈谈项目管理
- java中map的排序问题
- js中的"=="和equals()以及is()三者的区别
- SYN攻击检测与预防
- 路由基础(二)静态路由
- 玩转Excel系列-index+match查找函数用法
- 霍夫曼编码与priority_queue的千丝万缕
- Ubuntu下SVN的安装及使用方法
- Android WebView 开发详解(三)
- Jenkins+Maven+Git+Tomcat快速搭建持续集成环境