集合之六:Map接口

Map接口概述

  Map接口中的集合和Collection接口中的集合在存储数据的格式上有很大的不同,Map接口下的内容是以<K , V> ,键值对的形式存储的,我们查询API,Map接口的描述是:

  将键映射到值的对象。一个映射不能包含重复的键每个键最多只能映射到一个值

Map接口常用实现类:

  • HashMap
    • 无序,键不可重复
    • 键和值都允许使用null 
  • LInkedHashMap
    • 线程不安全
    • 使用双向链表来维护key-value对的次序,该链表定义了迭代顺序,该迭代顺序与key-value对的插入顺序保持一致。
  • HashTable
    • 线程安全
    • 不容许使用null作为key和value
    • 不常用,现已被Properties类代替

Map的常用方法

  

 package com.shsxt.lisa;

 import java.util.Collection;
import java.util.HashMap;
import java.util.Map; /*
* Map接口中的常用方法
* 使用Map接口的实现类 HashMap
*/
public class MapDemo01 { public static void main(String[] args) { function2(); } /*
* put(K,V) ---> 将键值对存储到集合中
* 返回值: 一般情况下 返回值是null,当储存重复键时 会返回被覆盖的值
*/
public static void function() {
//
Map<String,Integer> map = new HashMap<>();
map.put("张二狗", 12);
map.put("zhang",13);
//有重复键时 后者会将前者覆盖
int i=map.put("zhang",2);
System.out.println(i);//当储存重复键时 会返回被覆盖的值 } /*
* get(K) ---> 通过键取对应的值
* 返回值: 一般情况下 返回值是null,当储存重复键时 会返回被覆盖的值
*/
public static void function1() {
Map<Integer, String> map=new HashMap<>();
map.put(1, "张三丰");
map.put(2, "张二二");
map.put(3, "张思思"); //
String string = map.get(5);
//如果集合中没有这个键 方法返回空
System.out.println(string);
} /*
* 移除集合中的键值对
* remove(K)---->返回 V
*/ public static void function2() {
Map<Integer, String> map=new HashMap<>();
map.put(1, "张三丰");
map.put(2, "张二二");
map.put(3, "张思思"); //返回被删掉的值
String string = map.remove(1);
//如果集合中没有这个键 方法返回空
System.out.println(string);
}
}

Map集合遍历的方式

  1. entrySet方法 键值对的映射关系(Entry键值对对象) 获取
  2. 通过keySet() 方法 获取Map集合中所有的键,由于键是唯一的,所以返回一个Set集合存储所有的键

     import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map; public class TestMap {
    public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(1, "a");
    map.put(2, "b");
    map.put(3, "ab");
    map.put(4, "ab");
    map.put(4, "ab");// 和上面相同 , 会自己筛选
    System.out.println(map.size());
    // 第一种:
    /*
    * Set<Integer> set = map.keySet(); //得到所有key的集合
    *
    * for (Integer in : set) { String str = map.get(in);
    * System.out.println(in + " " + str); }
    */
    System.out.println("第一种:通过Map.keySet遍历key和value:");
    for (Integer in : map.keySet()) {
    //map.keySet()返回的是所有key的值
    String str = map.get(in);//得到每个key多对用value的值
    System.out.println(in + " " + str);
    }
    // 第二种:
    System.out.println("第二种:通过Map.entrySet使用iterator遍历key和value:");
    Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
    while (it.hasNext()) {
    Map.Entry<Integer, String> entry = it.next();
    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    }
    // 第三种:推荐,尤其是容量大时
    System.out.println("第三种:通过Map.entrySet遍历key和value");
    for (Map.Entry<Integer, String> entry : map.entrySet()) {
    //Map.entry<Integer,String> 映射项(键-值对) 有几个方法:用上面的名字entry
    //entry.getKey() ;entry.getValue(); entry.setValue();
    //map.entrySet() 返回此映射中包含的映射关系的 Set视图。
    System.out.println("key= " + entry.getKey() + " and value= "
    + entry.getValue());
    }
    // 第四种:
    System.out.println("第四种:通过Map.values()遍历所有的value,但不能遍历key");
    for (String v : map.values()) {
    System.out.println("value= " + v);
    }
    }
    }

练习题

1.分析以下需求,并用代码实现:
(1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)
(2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value
(3)利用四种方式遍历Map集合中的内容,格式:key::value

 package com.shsxt.homework;

 import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; /*
* 1.分析以下需求,并用代码实现:
(1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)
(2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value
(3)利用四种方式遍历Map集合中的内容,格式:key::value
*/
public class Homework01 { public static void main(String[] args) {
Map<Student,String> map = new HashMap<>();
map.put(new Student("张二狗",12),"大理国内的村子");
map.put(new Student("元首",10),"啦啦啦德玛西亚");
map.put(new Student("BigBean",23),"克苏鲁大陆"); //1 keyset
Set<Student> set=map.keySet();
for(Student s : set){
System.out.println(s+"::"+map.get(s));
}
System.out.println("-------------"); //2 entry
Set<Entry<Student, String>> entrySet = map.entrySet();
Iterator<Entry<Student, String>> it=entrySet.iterator();
while(it.hasNext()){
Entry<Student, String> entry= it.next();
System.out.println(entry.getKey()+"::"+entry.getValue());
} System.out.println("-------------");
//第三种 :推荐 尤其是容量大时
System.out.println("第三种:通过Map.entrySet遍历key和value");
for(Map.Entry<Student, String> entry:map.entrySet()){
System.out.println(entry.getKey()+"::"+entry.getValue());
} System.out.println("-------------");
// 第四种:
System.out.println("第四种:通过Map.values()遍历所有的value,但不能遍历key");
for(String string:map.values()){
System.out.println("value = "+ string);
}
} }
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();
// TODO Auto-generated constructor stub
} @Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
} }

2.分析以下需求,并用代码实现:
(1)利用键盘录入,输入一个字符串
(2)统计该字符串中各个字符的数量
(3)如:
用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
程序输出结果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)

 package com.shsxt.homework;

 import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap; /*
* 2.分析以下需求,并用代码实现:
(1)利用键盘录入,输入一个字符串
(2)统计该字符串中各个字符的数量
(3)如:
用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
程序输出结果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
*/
public class Homework02 { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串: ");
String str = sc.nextLine();
System.out.println("您输入的是: "+ str); //String str="If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java";
//String str="Happy Happy";
char ch[]= new char[20];
ch=str.toCharArray();
String res=getTimes(str);
System.out.println(res); } public static String getTimes(String str){
//1 将字符串转成字符串数组
char ch[]=str.toCharArray();
//2 创建一个map\集合 将字符和出现的次数存储到集合中
Map<Character, Integer> map= new TreeMap<>();
//3 遍历字符数组
for(char c :ch){
map.put(c,map.get(c)!= null?map.get(c)+1:1);
}
//4 创建StringBuffer
StringBuffer sb = new StringBuffer();
//5 遍历map集合
for(Map.Entry<Character, Integer> entry : map.entrySet()){
sb.append(entry.getKey()).append("(").append(entry.getValue()).append(")");
}
//6 返回StirngBuffer return sb.toString();
} }
上一篇:(转)使用 PyInstaller 把python程序 .py转为 .exe 可执行程序


下一篇:java 统计字符串中连续重复的字符,并得出新字符串