java map - yaokun123/php-wiki GitHub Wiki

集合Map

Map:一次添加一对元素。也称双列集合。
Collection:一次添加一个元素。也称单列集合。

其实map集合中存储的就是键值对。map集合必须保证键的唯一性。

一、常用方法

1、添加
Value put(key,value):返回前一个和key关联的值,如果没有返回null。

2、删除
void clear():清空map集合
value remove(key):根据指定的key删除这个键值对

3、判断
boolean containsKey(key);
boolean containsValue(value);
boolean isempty();

4、获取
value get(key):通过键获取值,如果没有该键值返回null
int size():获取键值对的个数

二、常用方法演示

import java.util.Map
public class MapDemo{
    public static void main(String[] args){
        Map<Integer,String> map = new HashMap<Integer,String>();
        this.method(map);
    }

    public static void method(Map<Integer,String> map){//学号和姓名
        //添加元素
        System.out.println(map.put(8,"test1"));//null
        System.out.println(map.put(8,"haha"));//test1

         System.out.println(map);//{8=haha}

         //删除
         System.out.println(map.remove(8));//haha

        //判断
        System.out.println(map.containsKey(8));//false

       //获取
       System.out.println(map.get(8));//null

      //取出map中的所有元素。
      //原理,通过keySet方法获取map中所有的键所在的set集合,再通过Set的迭代器获取到每一个键
      //在对每一个键获取其对应的值即可
      Set<Integer> keySet = map.keySet();
      Iterator<Integer> it = keySet.inerator();
      while(it.hasNext()){
          Integer key = it.next();
          String value = map.get(key);
          System.out.println(key);
          System.out.println(value);
      }

      //另外一种方法:通过Map转成set就可以迭代
      //找到了另一个方法,entrySet。
      //该方法将键和值的映射关系作为对象存储到了Set集合中,而这个映射关系的类型就是Map.Entry类型(结婚证)
      Set<Map.Entry<Integer,String>> entrySet = map.entrySet();
      Iterator<Map.Entry<Integer,String>> it = entrySet.inerator();
      while(it.hasNext()){
          Map.Entry<Integer,String> me = it.next();
          Integer key = me.getKey();
          String value = me.getValue();
          System.out.println(key+"..."+value);
      }
    }


    Collection<String> values = map.values();
    IteratorString> it = values.inerator();
    while(it.hasNext()){
          System.out.println(it.next());
    }
}

三、Map集合常见子类对象

Hashtable:内部结构是哈希表,是同步的。不允许null作为键,null作为值。
    Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。
HashMap:内部结构是哈希表,不是同步的。允许null作为键,null作为值。
TreeMap:内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。
⚠️ **GitHub.com Fallback** ⚠️