Java - collection 2-5 (Map)

Map

Overview and usage of Map collection

Overview of the Map collection

  • Interface Map<K,V> K: type of key; V: type of value
  • An object mapping keys to values; cannot contain duplicate keys; each key can map to at most one value
  • Example: student ID and name
    001 Xiaobai
    002 Xiaohei
    003 Xiaohong

Create an object of the Map collection

  • polymorphic way
  • The specific implementation class HashMap
import java.util.HashMap;
import java.util.Map;

/*
Map集合概述

- Interface Map<K,V> K:键的类型;V:值的类型
- 将键映射到值的对象;不能包含重复的键;每个键可以映射到最多一个值
- 举例:学生的学号和姓名
001 小白
002 小黑
003 小红

创建Map集合的对象

- 多态的方式
- 具体的实现类HashMap
*/
public class MapDemo {
    
    
	public static void main(String[] args) {
    
    
		//创建集合对象
		Map<String, String> map = new HashMap<String, String>();//HashMap保证了键的唯一性

		//添加方法:V put(K key,V value)将指定的值与该映射中的指定键相关联
		map.put("001", "小白");
		map.put("002", "小黑");
		map.put("003", "小红");
		map.put("003", "小绿");//当键重复时,会把原先的值替代调

		//输出集合对象
		System.out.println(map);

	}
}

Running results:
insert image description here
Basic functions of the Map collection

method name illustrate
V put(K key,V value) add element
V remove(Objedt key) Delete key-value pair elements based on key
void clear() remove all key-value elements
boolean containsKey(Object key) Determine whether the collection contains the specified key
boolean containsValue(Object value) Determine whether the collection contains the specified value
boolean isEmpty() Determine whether the collection is empty
int size() The length of the collection, that is, the number of key-value pairs in the collection
import java.util.HashMap;
import java.util.Map;

public class MapDemo {
    
    
	public static void main(String[] args) {
    
    
		//创建集合对象
		Map<String, String> map = new HashMap<String, String>();//HashMap保证了键的唯一性

		//添加方法:V put(K key,V value)将指定的值与该映射中的指定键相关联
		map.put("小黑", "小白");
		map.put("小绿", "小红");
		map.put("小蓝", "小紫");

		//V remove(Objedt key)根据键删除键值对元素
		System.out.println(map.remove("小蓝"));//返回小紫
		System.out.println(map.remove("小黄"));//返回null

		//void clear()移除所有的键值对元素
		map.clear();//{}

		//boolean containsKey(Object key)判断集合是否包含指定的键
		System.out.println(map.containsKey("小黑"));//true
		System.out.println(map.containsKey("小白"));//false

		//boolean containsValue(Object value)判断集合是否包含指定的值
		System.out.println(map.containsValue("小红"));//true
		System.out.println(map.containsValue("小绿"));//false

		//boolean isEmpty()判断集合是否为空
		System.out.println(map.isEmpty());//false

		//int size()集合的长度,也就是集合中键值对的个数
		System.out.println(map.size());//3

		//输出集合对象
		System.out.println(map);

	}
}

The acquisition function of the Map collection

method name illustrate
V get(Object key) get value by key
Set keySet() Get the set of all keys
Collection values() Get a collection of all values
Set<Map.Entry<K,V>>entrySet() Get a collection of all key-value pair objects
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
Map集合的获取功能

V get(Object key)  根据键获取值 
Set<K> keySet()获取所有键的集合
Collection<V> values()获取所有值的集合
*/
public class MapDemo2 {
    
    
	public static void main(String[] args) {
    
    
		//创建集合对象
		Map<String, String> map = new HashMap<String, String>();

		//添加元素
		map.put("小黑", "小白");
		map.put("小绿", "小红");
		map.put("小蓝", "小紫");

		//V get(Object key)  根据键获取值 
		//		System.out.println(map.get("小黑"));//小白
		//		System.out.println(map.get("小小"));//null

		//Set<K> keySet()获取所有键的集合
		//		System.out.println(map.keySet());//[小蓝, 小黑, 小绿]
		//遍历键集合
		Set<String> ks = map.keySet();
		for (String s : ks) {
    
    
			System.out.println(s);
		}

		//Collection<V> values()获取所有值的集合
		//		System.out.println(map.values());//[小紫, 小白, 小红]
		//遍历值集合
		Collection<String> v = map.values();
		for (String s : v) {
    
    
			System.out.println(s);
		}

	}
}

Running result:
insert image description here
traversal of the Map collection

  • Method 1:
    Obtain the set of all keys, use the KeySet() method to
    traverse the set of keys, get each key, use enhanced for to
    find the value according to the key, and use the get(Object key) method to achieve
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
Map集合的获取功能

V get(Object key)  根据键获取值 
Set<K> keySet()获取所有键的集合
Collection<V> values()获取所有值的集合
*/
public class MapDemo2 {
    
    
	public static void main(String[] args) {
    
    
		//创建集合对象
		Map<String, String> map = new HashMap<String, String>();

		//添加元素
		map.put("小黑", "小白");
		map.put("小绿", "小红");
		map.put("小蓝", "小紫");

		//Set<K> keySet()获取所有键的集合
		//遍历键集合
		Set<String> ks = map.keySet();
		for (String k : ks) {
    
    
			String v = map.get(k);
			System.out.println(k + "," + v);
		}

	}
}

operation result:
insert image description here

  • Method 2
    Obtain the collection of all key-value pair objects Use Set<Map.Entry<K,V>>entrySet()
    to traverse the collection of key-value pair objects to obtain each key-value pair object, and use enhanced for to obtain each Map .Entry
    gets the key and value according to the key-value pair object, use **getKey() to get the key, use getValue()** to get the value

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/*
Map集合的获取功能

V get(Object key)  根据键获取值 
Set<K> keySet()获取所有键的集合
Collection<V> values()获取所有值的集合
*/

/*
方式二
获取所有键值对对象的集合 用**Set<Map.Entry<K,V>>entrySet()**
遍历键值对对象的集合,得到每一个键值对对象,用增强for实现,得到每一个**Map.Entry**
根据键值对对象获取键和值,用**getKey()**得到键,用**getValue()**得到值
*/

public class MapDemo2 {
    
    
	public static void main(String[] args) {
    
    
		//创建集合对象
		Map<String, String> map = new HashMap<String, String>();

		//添加元素
		map.put("小黑", "小白");
		map.put("小绿", "小红");
		map.put("小蓝", "小紫");

		//获取所有键值对对象的集合
		Set<Entry<String, String>> es = map.entrySet();

		//遍历键值对对象的集合,得到每一个键值对对象

		for (Entry<String, String> me : es) {
    
    
			//根据键值对对象获取键和值
			String key = me.getKey();
			String value = me.getValue();
			System.out.println(key + "," + value);
		}

	}
}

operation result:
insert image description here

Case: HashMap collection stores student objects and traverses

Requirements: Create a HashMap collection, the key is the student number (String), and the value is the student object (Student). Store three key-value pair elements and traverse


//定义学生类
public class Student {
    
    
	private String name;
	private int age;

	public String getName() {
    
    
		return name;
	}

	public void setName(String name) {
    
    
		this.name = name;
	}

	public int getAge() {
    
    
		return age;
	}

	public void setAge(int age) {
    
    
		this.age = age;
	}

	public Student(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}

	public Student() {
    
    
		super();
	}

}

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/*
案例:HashMap集合存储学生对象并遍历
需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student)。
存储三个键值对元素,并遍历
*/
public class HashMapDemo {
    
    
	public static void main(String[] args) {
    
    
		//创建集合对象
		Map<String, Student> map = new HashMap<String, Student>();
		//创建学生对象
		Student s1 = new Student("小白", 12);
		Student s2 = new Student("小黑", 15);
		Student s3 = new Student("小红", 13);
		//添加元素到集合
		map.put("001", s1);
		map.put("002", s2);
		map.put("003", s3);

		//遍历一:键找值
		Set<String> keySet = map.keySet();
		for (String k : keySet) {
    
    
			Student v = map.get(k);
			System.out.println(k + "," + v.getName() + "," + v.getAge());
		}
		System.out.println("--------");
		//遍历二:键值对找键和值
		Set<Entry<String, Student>> entrySet = map.entrySet();
		for (Entry<String, Student> e : entrySet) {
    
    
			String k = e.getKey();
			Student v = e.getValue();
			System.out.println(k + "," + v.getName() + "," + v.getAge());
		}
	}
}

operation result:
insert image description here

Case: HashMap collection stores student objects and traverses (2)

Requirements: Create a HashMap collection, the key is the student number (String), and the value is the student object (Student). Store three key-value pair elements and traverse them.
Requirements: Ensure the uniqueness of the key. If the member variable values ​​of the student objects are the same, we consider them to be the same object

import java.util.Objects;

//定义学生类
public class Student {
    
    
	private String name;
	private int age;

	public String getName() {
    
    
		return name;
	}

	public void setName(String name) {
    
    
		this.name = name;
	}

	public int getAge() {
    
    
		return age;
	}

	public void setAge(int age) {
    
    
		this.age = age;
	}

	public Student(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}

	public Student() {
    
    
		super();
	}

	//重写两个方法
	@Override
	public int hashCode() {
    
    
		return Objects.hash(age, name);
	}

	@Override
	public boolean equals(Object obj) {
    
    
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		return age == other.age && Objects.equals(name, other.name);
	}

}
import java.util.HashMap;
import java.util.Set;

/*
案例:HashMap集合存储学生对象并遍历
需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student)。
存储三个键值对元素,并遍历
要求:保证键的唯一性,如果学生对象的成员变量值相同,我们就认为是同一个对象
*/
public class HashMapDemo {
    
    
	public static void main(String[] args) {
    
    
		//创建集合对象
		HashMap<Student, String> map = new HashMap<Student, String>();
		//创建学生对象
		Student s1 = new Student("小白", 12);
		Student s2 = new Student("小黑", 15);
		Student s3 = new Student("小红", 13);
		Student s4 = new Student("小红", 13);

		//添加元素到集合
		map.put(s1, "北京");
		map.put(s2, "南京");
		map.put(s3, "深圳");
		map.put(s4, "湖南");//成员变量值相同,值覆盖上面的值

		//遍历一:键找值
		Set<Student> keySet = map.keySet();
		for (Student k : keySet) {
    
    
			String v = map.get(k);
			System.out.println(k.getName() + "," + k.getAge() + v);
		}

	}
}

operation result:
insert image description here

Case: ArrayList collection stores HashMap elements and traverses (collection nesting)

Requirements: Create an ArrayList collection, store three elements, each element is a HashMap, the key and value of each HashMap are String, and traverse

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

/*
案例:ArrayList集合存储HashMap元素并遍历
需求:创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap,
	每一个HashMap的键和值都是String,并遍历
*/
public class ArrayListDemo {
    
    
	public static void main(String[] args) {
    
    
		//创建ArrayList集合对象
		ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();

		//创建HashMap集合对象,添加键值对元素
		HashMap<String, String> hm1 = new HashMap<String, String>();
		hm1.put("小白", "大白");
		hm1.put("小黑", "大黑");
		array.add(hm1);

		HashMap<String, String> hm2 = new HashMap<String, String>();
		hm2.put("小红", "大红");
		hm2.put("小蓝", "大蓝");
		array.add(hm2);

		HashMap<String, String> hm3 = new HashMap<String, String>();
		hm3.put("小绿", "大绿");
		hm3.put("小紫", "大紫");
		array.add(hm3);

		//遍历ArrayList集合
		for (HashMap<String, String> hm : array) {
    
    
			//遍历HashMap集合
			Set<String> keySet = hm.keySet();
			for (String k : keySet) {
    
    
				String v = hm.get(k);
				System.out.println(k + "," + v);
			}

		}

	}
}

operation result:
insert image description here

Case: HashMap collection stores ArrayList elements and traverses (collection nesting)

Requirement: Create a HashMap collection, store three elements, the key of each key-value pair element is String, the value is ArrayList, and the element of each ArrayList is String, and traverse

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

/*
案例:HashMap集合存储ArrayList元素并遍历(集合嵌套)

需求:创建一个HashMap集合,存储三个元素,每一个键值对元素的键都是String,值是ArrayList,
每一个ArrayList的元素都是String,并遍历
*/
public class HashMapDemo2 {
    
    
	public static void main(String[] args) {
    
    
		//创建HashMap集合对象
		HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();

		//创建ArrayList集合对象,添加元素
		ArrayList<String> a1 = new ArrayList<String>();
		a1.add("小白");
		a1.add("大白");
		hm.put("001", a1);

		ArrayList<String> a2 = new ArrayList<String>();
		a2.add("小黑");
		a2.add("大黑");
		hm.put("002", a2);

		ArrayList<String> a3 = new ArrayList<String>();
		a3.add("小红");
		a3.add("大红");
		hm.put("003", a3);

		//遍历HashMap集合
		Set<String> keySet = hm.keySet();
		for (String k : keySet) {
    
    
			System.out.println(k);
			ArrayList<String> v = hm.get(k);
			//遍历ArrayList集合
			for (String s : v) {
    
    
				System.out.println("  " + s);
			}
		}

	}
}

operation result:
insert image description here

Case: Count the number of occurrences of each character in a string

Requirement: Input a string by keyboard, and count the number of occurrences of each string in the string
Example: Input by keyboard: "aababcabcdabcde" Output on console: "a(5)b(4)c(3)d(2) e(1)"

import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

/*
案例:统计字符串中每个字符出现的次数

需求:键盘录入一个字符串,要求统计字符串中每个字符串出现的次数
举例:键盘录入:“aababcabcdabcde” 
	在控制台输出:“a(5)b(4)c(3)d(2)e(1)”
	
	
字符对应字符次数,可以通过HashMap集合存储,
	键是字符(Character),值是字符次数(Integer)
	
*/
public class HashMapDemo3 {
    
    
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);

		System.out.println("请输入一个字符串:");
		String line = sc.nextLine();

		//创建HashMap集合对象
		//键是字符(Character),值是字符次数(Integer)
		HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
//		TreeMap<Character, Integer> hm=new TreeMap<Character, Integer>();//对键(字符)自然排序 
 
		//遍历字符串
		for (int i = 0; i < line.length(); i++) {
    
    
			char key = line.charAt(i);

			//将字符作为键,到HashMap中找对应,返回值null,值为1,返回值不为null,值+1
			Integer value = hm.get(key);

			if (null == value) {
    
    
				hm.put(key, 1);
			} else {
    
    
				value++;
				hm.put(key, value);
			}

		}

		//遍历HashMap集合,按照要求拼接
		StringBuilder sb = new StringBuilder();//用于拼接

		Set<Character> keySet = hm.keySet();
		for (Character k : keySet) {
    
    
			Integer v = hm.get(k);
			sb.append(k).append("(").append(v).append(")");
		}

		String string = sb.toString();//转换为string
		System.out.println(string);//输出结果

	}
}

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_47678894/article/details/119422772