JAVA基础集合之Map、HashMap、LinkedHashMap、TreeMap

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_22067469/article/details/82184248

Map集合

  • Map是属于java.util的一个接口Map<K,V>

    K - 映射所维护的键的类型
    V - 映射值的类型
    Map是将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值

  • Map接口和Collection接口的不同

    Map是双列的,Collection是单列的
    Map的键唯一,Collection的Set是唯一的
    Map集合的数据结构值针对键有效,跟值无关
    Collection集合的数据结构是针对元素有效

Map集合的功能使用

  • Map集合的功能概述(一)
//1.创建一个Map对象,一般都HashMap这个子类
Map<String,String> map = new HashMap<String,String>();

//2.添加功能
// put(K key,V value):添加元素。
// 2.1如果键是第一次存储,就直接存储元素,返回null
// 2.1如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
String value = map.put("name", "zhangsan");
System.out.println(value);

value = map.put("name", "lisi");
System.out.println(value);

map.put("age", "30");
map.put("gender", "男");
System.out.println("map:" + map);

/*3.删除功能
// void clear():移除所有的键值对元素
// V remove(Object key):根据键删除键值对元素,并把值返回*/
map.clear();
value = map.remove("gender");
System.out.println("移除元素:" + value);
System.out.println("map:" + map);

4.判断功能
// boolean containsKey(Object key):判断集合是否包含指定的键
// System.out.println(map.containsKey("name1"));

// boolean containsValue(Object value):判断集合是否包含指定的值
// System.out.println(map.containsValue("男1"));

// boolean isEmpty():判断集合是否为空
map.clear();
System.out.println("集合是否为空:" + map.isEmpty());
  • Map集合的功能概述(二)
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", "zhangsan");
map.put("age", 30);//int 提升为Integer 【自动装箱】
map.put("gender", '男');//char 提升Character
map.put("height", 1.89);

// 1.获取功能
// V get(Object key):根据键获取值
System.out.println(map.get("name"));
System.out.println(map.get("age"));
System.out.println(map.get("gender"));

// Set<K> keySet():获取集合中所有键的集合
Set<String> keys = map.keySet();
System.out.println("map所有的键:" + keys);

// Collection<V> values():获取集合中所有值的集合
Collection<Object> values =  map.values();
System.out.println("map所有的值:" + values.getClass());

// 2.长度功能
// int size():返回集合中的键值对的个数
System.out.println("map的長度:" + map.size());
  • Map集合的遍历一(键找值)
//1.创建Map对象
Map<String,String> map = new HashMap<String,String>();
map.put("name", "刘三姐");
map.put("age", "48");
map.put("gender", "女");
map.put("height", "1.62");

//2.取key对应的值
// String name = map.get("name");
// String age = map.get("age");
// String gender = map.get("gender");
// System.out.println("name:" + name);
// System.out.println("age:" + age);
// System.out.println("gender:" + gender);

//3.遍历
//3.1获取map所有键
Set<String> keys = map.keySet();
//3.2遍历键
for(String key : keys){
    //3.3 通过key获取值
    String value =  map.get(key);
    //打印key&value
    System.out.println(key + " : " + value);
}
  • Map集合的遍历二(键值对对象 (Entry)找键和值)
//1.创建Map对象
Map<String,String> map = new HashMap<String,String>();
map.put("name", "刘三姐");
map.put("age", "48");
map.put("gender", "女");
map.put("height", "1.62");

//java.util.Map.Entry
/**
 * Entry:称为键值对 对象
 * */
Set<Entry<String, String>> entries = map.entrySet();
//遍历
for(Entry<String, String> entry : entries){
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key + " : " + value);
}

//1.创建Map
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("zhangsan", 100);
map.put("lisi", 89);
map.put("wangwu", 1000);

//2.遍历
Set<Entry<String, Integer>> entries = map.entrySet();

//2.1通过增强for循环来遍历Set
for(Entry<String, Integer> entry : entries){
    //Map.Entry 的实现类HashMap$Node 
    System.out.println(entry.getClass());
    System.out.println(entry.getKey() + "---" + entry.getValue());
}

//2.2 通过迭代器来遍历Set
Iterator<Entry<String, Integer>>  iterator = entries.iterator();
while(iterator.hasNext()){
    Entry<String, Integer> entry = iterator.next();
    System.out.println(entry.getKey() + "---" + entry.getValue());
}
  • LinkedHashMap的概述和使用
    LinkedHashMap的特点:底层是链表实现的可以保证怎么存就怎么取
    HashMap是存的和取的顺序是不一样的
Map<String,String> map = new LinkedHashMap<String,String>();
map.put("zhangsan", "广州");
map.put("lisi", "广西");
map.put("wangwu", "湖南");
map.put("zhaoliu", "湖北");
map.put("xiaoqi", "福建");

//遍历
Set<Entry<String, String>> entries = map.entrySet();
for(Entry<String, String> entry : entries){
    System.out.println(entry.getKey() + "--" + entry.getValue());
}

//最方便遍历方式
//Set<Entry<String, String>> entries = map.entrySet();
for(Entry<String, String> entry : map.entrySet()){
    System.out.println(entry.getKey() + "--" + entry.getValue());
}
  • TreeMap集合键是Student值是String
//使用Comparator进行TreeMap的key排序
public static void test3() {
    Map<Student,String> map = new TreeMap<Student,String>(new Comparator<Student>() {

        @Override
        public int compare(Student o1, Student o2) {
            // TODO Auto-generated method stub
            //按名字字母的倒序排序
            int num = o2.name.compareTo(o1.name);
            num = num == 0 ? 1 : num;//同名的可以存储
            return num;
        }
    });
    map.put(new Student("banana", 18), "gz");
    map.put(new Student("cc", 18), "sz");
    map.put(new Student("apple", 18), "xg");
    map.put(new Student("cc", 28), "sz");

    for(Entry<Student,String> entry :map.entrySet()){
        System.out.println(entry.getKey() + " - " + entry.getValue());
    }
}
//使用Comparable进行TreeMap的key排序
public static void test2() {
    Map<Student,String> map = new TreeMap<Student,String>();
    map.put(new Student("banana", 18), "gz");
    map.put(new Student("cc", 18), "sz");
    map.put(new Student("apple", 18), "xg");
    map.put(new Student("cc", 28), "sz");

    for(Entry<Student,String> entry :map.entrySet()){
        System.out.println(entry.getKey() + " - " + entry.getValue());
    }
}

public static void test1() {
    Map<String,String> map = new TreeMap<String,String>();
    map.put("zhangsan", "广州");
    map.put("lisi", "广西");
    map.put("wangwu", "湖南");
    map.put("zhaoliu", "湖北");
    map.put("xiaoqi", "福建");

    //最方便遍历方式
    //Set<Entry<String, String>> entries = map.entrySet();
    for(Entry<String, String> entry : map.entrySet()){
        System.out.println(entry.getKey() + "--" + entry.getValue());
    } 
}

class Student implements Comparable<Student>{
    String name;
    int age;
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
    @Override
    public int compareTo(Student o) {
        // TODO Auto-generated method stub
        //按名字字母排序
        int num = this.name.compareTo(o.name);

        //同名的可以存储
        num = num == 0 ? 1 : num;
        return num;
    }
}
  • 统计字符串中每个字符出现的次数
String str = "aaaabbbccccc";
//1.创建存储字符次数的Map集合
Map<Character,Integer> map = new HashMap<Character,Integer>();

//2.遍历字符串的每一个字符
for(int i=0;i<str.length();i++){
    //3.往map里添加字符出现次数(累加)
    char ch = str.charAt(i);
    //map第一次出现这个字符
    if(!map.containsKey(ch)){
        map.put(ch, 1);
    }else{
        //map如果不是第一 次出现这个字符,累加+1
        map.put(ch, map.get(ch) + 1);
    }
}

System.out.println("map:" + map);
  • HashMap和Hashtable的区别
    1.Hashtable是JDK1.0版本出现的,是线程安全的,效率低,有加锁
    2.HashMap是JDK1.2版本出现的,是线程不安全的,效率高
    3.Hashtable不可以存储null键和null值
    4.HashMap可以存储null键和null值
//hashMap对象
HashMap<String,String> map = new HashMap<String,String>();
map.put("name", "gyf");
map.put(null, null);
System.out.println(map);

//Hashtable对象
Hashtable<String,String> table = new Hashtable<String,String>();
table.put("name", "gyf");
table.put(null, null);//Hashtable不可以存储null键和null值
System.out.println(table);
  • Collections工具类的概述和常见方法

    Collection 与 Collections 区别
    Collection是一个接口
    Collections是一个类
    Collections的作用针对集合操作 的工具类

  • Collections成员方法

public static <T> void sort(List<T> list) 排序
public static <T> int binarySearch(List<?> list,T key) 二分查找
public static <T> T max(Collection<?> coll)
public static void reverse(List<?> list)
public static void shuffle(List<?> list)
List<Integer> list1 = new ArrayList<Integer>();
list1.add(23);
list1.add(2);
list1.add(3);
list1.add(13);
System.out.println("list1:" + list1);

//1.给list集合进行排序
//Collections.sort(list1);
//System.out.println("list1:" + list1);

//2.二分查找
//int index = Collections.binarySearch(list1, 13);
//System.out.println("13在list1中的位置:" + index);

//3.取最大值
int max = Collections.max(list1);
System.out.println("最大值:" + max);

//4.reverse 反转
Collections.reverse(list1);
System.out.println("反转后的list1" + list1);

//5.shuffle 打乱顺序
Collections.shuffle(list1);
System.out.println("打乱后的list1" + list1);

猜你喜欢

转载自blog.csdn.net/qq_22067469/article/details/82184248