java版本: 把手机号码里重复数字出现的次数按从多到少排列打印出来

参考资料:

http://www.cnblogs.com/liu-qing/p/3983496.html

http://lhkzyz.iteye.com/blog/1666193

http://blog.csdn.net/fygkchina/article/details/8764501



看到: https://hui.lu/a-python-interview/ blog中的面试题目 "手机号码里重复数字出现的次数按从多到少排列打印出来"

文中作者给出了python的实现。


参考了下大家的文章,总结了下java的实现,做个笔记。


思路: 按照http://www.cnblogs.com/liu-qing/p/3983496.html中提到的:"可以先将map中的key-value放入list,然后用Collections.sort对list排序,再将排序后的list放入LinkedHashMap,最后返回LinkedHashMap就可以了。"



import java.util.*;

/**
 * Created by dell on 2016/8/26.
 */
public class Test003 {
    public static void main(String[] args) {
        String phoneNum = "18655448827";
        Map numMap = new HashMap();
        char[] ch = phoneNum.toCharArray();

        for (char c : ch) {
            if (numMap.get(c) == null) {
                numMap.put(c, 1);
            } else {
                int num = numMap.get(c);
                num++;
                numMap.put(c, num);
            }
        }

        numMap = sortByValue2(numMap);
        //取出key的集合
        Set set = numMap.keySet();

        for (Character c : set) {
            System.out.println("["+c+"]"+":出现的次数"+numMap.get(c));
        }


    }

    public static Map sortByValue(Map map) {
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
            // 将链表按照值得从小到大进行排序
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue());
            }
        });
        Map result = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext(); ) {
            Map.Entry entry = (Map.Entry) it.next();
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }


    /**
     * java 7 version
     * @param map
     * @param 
     * @param 
     * @return
     */
    public static > Map sortByValue2(Map map) {
        List> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });

        Map result = new LinkedHashMap<>();
        for (Map.Entry entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
}


你可能感兴趣的:(java文章)