HashMap

本文介绍了HashMap的基础知识,包括它的核心组成单位Entry和无序性的特点。详细讲述了HashMap的put()、putAll()、remove()、get()、KeySet()、getOrDefault()以及EntrySet()等常用方法的用法。此外,还提到了如何通过EntrySet遍历并排序HashMap,以及使用Comparator对HashMap进行排序的示例。

一、HashMap的简单介绍

HashMap是非常常见的一种数据结构,这种数据结构可以存储键值对(Key-Value)。

HashMap的主干是一个Entry数组,Entry是HashMap的基本组成单元,每个Entry包含一个键值对,所以HashMap可以看作是保存了两个对象之间映射关系的一种集合。

//HashMap的主干数组,可以看到就是一个Entry数组,初始值为空数组{}。
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

二、HashMap常用方法

1.put(),添加一个键值对

添加到map的数据与list不一样,是没有顺序的,其顺序根据哈希算法得出。

public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("aaa", 0);
        map.put("bbb", 1);

        System.out.println(map);
}

2.putAll()

可以把一个HashMap集合对象,整体加入到另外一个HashMap对象中。

public static void main(String[] args) {
        HashMap<String, Integer> map1 = new HashMap<>();

        map1.put("aaa", 0);
        map1.put("bbb", 1);
        
        HashMap<String, Integer> map2 = new HashMap<>();
        map2.putAll(map1);
        System.out.println(map2);
}

 

 3.remove(),删除一个键值对

remove方法内是针对Key进行删除的。

public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("aaa", 0);
        map.put("bbb", 1);
        System.out.println(map);

        map.remove("aaa");
        System.out.println(map);
}

 

4.get(),查询value

传入key,就可以查询到value。

public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("aaa", 0);
        map.put("bbb", 1);
        
        System.out.println(map.get("aaa"));
}

 

5.KeySet()

先使用keySet函数,获取到HashMap的所有Key的集合对象,然后循环所有的key,通过HashMap的get方法,获取到对应的value。

KeySet只是处理HashMap中的Key,不会对Value进行处理,需要搭配get()获取对应键的值。

public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("aaa", 0);
        map.put("bbb", 1);

        Set<String> set = map.keySet();
        for(String s : set){
            System.out.println(s + "--" + map.get(s));
        }
}

 

6.getOrDefault()

是在哈希表中搜索是否存在该方法参数列表中的key值,如果存在该key值,则返回哈希表中该key值对应的vakue值;如果不存在,则返回该方法参数列表中的default值。

 public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("aaa", 1);
        map.put("ccc", 0);
        map.put("bbb", 3);
        map.put("ddd", 2);

        int a = map.getOrDefault("aaa",-1);
        int e = map.getOrDefault("eee",-1);
        System.out.println(a);
        System.out.println(e);
}

 

 案例:可以查找是否存在该键,并且改变值的大小。

public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("aaa", 1);
        map.put("ccc", 0);
        map.put("bbb", 3);
        map.put("ddd", 2);

        System.out.println(map);
        //存在aaa就+10
        int a = map.getOrDefault("aaa",-1) + 10;

        map.put("aaa",a);
        System.out.println(map);
}

 

7.**EntrySet()

遍历:可以得到一个Entry对象的结果集,然后使用Entry对象的getKey和getValue方法获取键与值。

public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("aaa", 0);
        map.put("bbb", 1);

        Set<Map.Entry<String, Integer>> entries = map.entrySet();

        for(Map.Entry<String, Integer> en : entries){
            System.out.println(en.getKey() + "++" + en.getValue());
        }
}

 

排序:调用Comparator接口和Collections.sort()方法,使用compareTo()和compare()方法对HashMap进行排序。

其中compare是静态的,可以通过类名直接调用.Integer.compare(a,b);
compareTo是非静态的,只能通过对象名.compareTo()来调用;

//compareTo
public int compareTo(Integer anotherInteger) {
    return compare(this.value, anotherInteger.value);
}

//compare
public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

Integer.compare(a,b)中顺序也是非常重要的,

compareTo内部其实也是直接调用的compare方法。
对象大于目标参数,返回1;
对象小于目标参数,返回-1;
对象等于目标参数,返回0;

public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        map.put("aaa", 1);
        map.put("ccc", 0);
        map.put("bbb", 3);
        map.put("ddd", 2);

        //compare需要List结构
        List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());

        //针对Key排序
        Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });

        //Java8引入Lambda表达式
        //entries.sort((o1, o2) -> o1.getKey().compareTo(o2.getKey()));

        for (int i = 0; i < entries.size(); i++) {
            String str = entries.get(i).toString();
            System.out.print(str + "  ");
        }System.out.println();

        //针对Value排序
        Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return Integer.compare(o1.getValue(),o2.getValue());
            }
        });

        //Lambda表达式
        //entries.sort((o1, o2) -> Integer.compare(o1.getValue(),o2.getValue()) );

        for (int i = 0; i < entries.size(); i++) {
            String str = entries.get(i).toString();
            System.out.print(str + "  ");
        }System.out.println();
}

 

排序案例:

对Map的value进行排序,如果value相同,那么则按照key进行排序。

private static Map<String, Integer> student = new HashMap<String, Integer>();
    private static List<Map.Entry<String, Integer>> lists;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        //输入字符串行数
        int totalNumber = sc.nextInt();
        //换行
        sc.nextLine();

        //声明一个字符串数组,不进行初始化
        String line[];
        //姓名
        String name;
        //身高
        int height;

        //遍历输入信息
        for (int i = 0; i < totalNumber; i++) {
            //使用split分割当前输入的这行字符串,将其初始化给line
            line = sc.nextLine().trim().split(" ");
            name = line[0];
            //将字符串解析为整型  “199” -> 199
            height = Integer.parseInt(line[1]);
            //添加进HashMap
            student.put(name, height);
        }

        //将HashMap的键值对以entry形式放入Lists中
        lists = new ArrayList<>(student.entrySet());

        //调用排序方法
        sort();

        //输出
        for (int i = 0; i < lists.size(); i++) {
            System.out.println(lists.get(i));
        }

    }

    //根据height and name 排序
    public static void sort() {
        /*Collections.sort(lists, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {

                //从小到大排序
                int status = Integer.compare(o1.getValue() ,o2.getValue());
                if (status == 0) {
                    //compare()方法内部只能比较Integer类型数据
                    status = o1.getKey().compareTo(o2.getKey());
                }
                return status;
            }
        });*/
        
        //Lambda表达式
        lists.sort((o1, o2) -> {
            //从小到大排序
            int status = Integer.compare(o1.getValue() ,o2.getValue());
            if (status == 0) {
                //compare()方法内部只能比较Integer类型数据
                status = o1.getKey().compareTo(o2.getKey());
            }
            return status;
        });
}

 

 

 

参考文献:java 实现对HashMap 的 key/value 进行排序_LawsonAbs的博客-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值