黑马程序员——Map接口

------ Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
Map接口
一.Map接口概述
    1、Map是一个键值对形式的集合。它的元素都是有键和值组成。
     2、特点:a、最大的优点就是体现对应关系
                     b、Map是一个键值对形式的集合。它的数据不再是单个的了,必须同时有键和值组成。
     3、Map和Collection的区别:
          a、Map:是(键值对)双列形式的集合;键必须是唯一的不能重复,值可以重复;可以看成是夫妻对的集合
          b、Collection:是单列值的集合;Collection的List儿子存储元素的时候是可以重复的。它的Set儿子是唯一
                的;可以看成是单身汉的集合。
     4、HashMap和Hashtable的区别?(面试题)
          a、HashMap:线程不安全,效率高。允许null键和值。
          b、Hashtable:线程安全,效率低。不允许null键和值。
二. Map接口的功能概述
    1、添加功能:
          V put(K key, V value) :当key在集合中不存在时,添加元素;当key在集合中存在的时候,替换元素。
     2、判断功能:
          boolean containsValue( Object value ):判断指定的值是否在集合中存在。
          boolean isEmpty():判断集合是否为空
      3、删除功能:
          void clear():清除所有键值对数据。
          V remove( Object key ):根据指定的键删除键值对
      4、获取功能
          Set<Map.Entry<K,V>> entrySet():键值对对象的集合。
          Object get( Object key ):根据键获取值
          Set<K> keySet():所有键的集合      
          Collection<V> values():所有值得
       5、长度功能
           int size():返回此映射中的键-值映射关系数。
三. Map接口的功能测试  
package Test1;

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

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

		//1.添加功能:
		// V put(K key,V value)
		// 添加元素,如果键存在,就替换。返回的值是根据键找到的。
		System.out.println(map.put("czbk004", "林心如"));
		System.out.println(map.put("czbk003", "林志炫"));
		System.out.println(map.put("czbk005", "林青霞"));
		System.out.println("map:"+map);
		System.out.println("------------------");

		//2.删除功能:
		// V remove(Object key):根据指定的键删除键值对。
		System.out.println("remove:" + map.remove("czbk003"));
		System.out.println("remove:" + map.remove("czbk007"));
		System.out.println("------------------");

		//3. 判断功能:
		// boolean containsKey(Object key):判断指定的键是否在集合中存在
		// boolean containsValue(Object vlaue):判断指定的值是否在集合中存在
		// boolean isEmpty():判断集合是否为空
		System.out.println("containsKey:" + map.containsKey("czbk003"));
		System.out.println("containsKey:" + map.containsKey("czbk007"));
		System.out.println("containsValue:"+map.containsValue("林青霞"));
		System.out.println("isEmpty:" + map.isEmpty());
		System.out.println("------------------");

		//4. 长度功能:
		// int size()
		System.out.println("size:" + map.size());
		System.out.println("------------------");

		// 遍历集合【根据键得到值:】
		Set<String> set=map.keySet();
		for(String key:set){
			String value=map.get(key);
			System.out.println(key+"--"+value);
		}
		System.out.println("------------------");
		// void clear():清除所有键值对数据。
		map.clear();
		System.out.println("map.clear()--map:"+map);
	}
}
运行结果:

四. Map的两种遍历方式:
     1、用迭代器的方式来做:前面功能测试已经体现。
     2、通过键值对对象来获取 键、值 的形式来做:
package Test1;

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

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

		// 2. 添加元素
		map.put("czbk004", "林心如");
		map.put("czbk003", "林志炫");
		map.put("czbk005", "林青霞");

		// 3. 遍历集合(输出集合对象名称)
		Set<Map.Entry<String, String>> k = map.entrySet(); // 获取键值对对象的Set集合 k 
		for (Map.Entry<String, String> str : k) {
			String key = str.getValue(); // 根据键值对对象 获取键
			String value = str.getKey(); // 根据键值对对象 获取值
			System.out.println(key + "--" + value);
		}
	}
}
五. HashMap
      1. 基于 哈希表 的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。
2. HashMap存储自定义对象并遍历(创建无参构造,所属对象类,重写HashCode()和 equals();“元素具备比较性”
package HashMap;

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

public class HashMapTest {
	public static void main(String[] args) {
		HashMap<Student, String> stu2 = new HashMap<Student, String>();
		stu2.put(new Student("林青霞", "26"), "004");
		stu2.put(new Student("刘涛", "30"), "005");
		stu2.put(new Student("李连杰", "26"), "006");
		stu2.put(new Student("李连杰", "26"), "006");
		Set<Student> set2 = stu2.keySet();
		for (Student s : set2) {
			String value = stu2.get(s);
			System.out.println("键:"+s.getName()+"--"+s.getAge()+"***"+"值:"+value);
		}
	}
}
package HashMap;

public class Student {
private String name;
private String age;
public Student() {
	super();
}
public Student(String name, String age) {
	super();
	this.name = name;
	this.age = age;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String getAge() {
	return age;
}
public void setAge(String age) {
	this.age = age;
}
	public int hashCode() {
		return this.name.hashCode()+this.age.hashCode();
	}
	public boolean equals(Object obj) {
	if (this==obj) {
		return true;
	}
	if(!(obj instanceof Student)){
		return false;
	}
	Student s=(Student)obj;
	return this.name.endsWith(s.getName())&&this.age.equals(s.getAge());
	
	}
}
运行结果如下:

六. TreeMap
1. TreeMap存储自定义对象为键 并遍历

键值对象具备比较性----通过构造方法,传入构造器(实现了comparable接口的对象),

而具有了比较的功能,进而具备了唯一性和排序的功能


import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import day30.test1.Student;

public class TreeMapTest {
public static void main(String[] args) {
	TreeMap<Student, String> tm=new TreeMap<Student,String>(new Comparator<Student>() {
		public int compare(Student s1, Student s2) {
			int num1=s1.getAge()-s2.getAge();
			int num2=(num1==0)?s1.getName().hashCode()-s2.getName().hashCode():num1;
			return num2;
		}
	});
	tm.put(new Student("林青霞",26), "001");
	tm.put(new Student("林青霞",26), "001");
	tm.put(new Student("林青",26), "002");
	tm.put(new Student("张曼玉",30), "003");
	tm.put(new Student("成龙",45), "004");
	Set<Entry<Student, String>> a= tm.entrySet();
	for(Map.Entry<Student, String> key:a){
		System.out.println("键-姓名:"+key.getKey().getName()+"--"+"年龄:"+key.getKey().getAge()+"-----"+"值:"+key.getValue());
	}
}
}
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import day30.test1.Student;

public class TreeMapTest {
public static void main(String[] args) {
	TreeMap<Student, String> tm=new TreeMap<Student,String>(new Comparator<Student>() {
		public int compare(Student s1, Student s2) {
			int num1=s1.getAge()-s2.getAge();
			int num2=(num1==0)?s1.getName().hashCode()-s2.getName().hashCode():num1;
			return num2;
		}
	});
	tm.put(new Student("林青霞",26), "001");
	tm.put(new Student("林青霞",26), "001");
	tm.put(new Student("林青",26), "002");
	tm.put(new Student("张曼玉",30), "003");
	tm.put(new Student("成龙",45), "004");
	Set<Entry<Student, String>> a= tm.entrySet();
	for(Map.Entry<Student, String> key:a){
		System.out.println("键-姓名:"+key.getKey().getName()+"--"+"年龄:"+key.getKey().getAge()+"-----"+"值:"+key.getValue());
	}
}
}
运行结果:

     2、 存储自定义对象为键并遍历(创建无参构造。所属对象类,重写HashCode()和 equals();“键对象具备比较性”
package day30.test1;

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

public class MapTest {
	public static void main(String[] args) {
		HashMap<Student, String> hm=new HashMap<Student,String>();
		hm.put(new Student("林青霞",26), "001");
		hm.put(new Student("林青霞",26), "001");
		hm.put(new Student("林青",26), "002");
		hm.put(new Student("张曼玉",30), "003");
		hm.put(new Student("成龙",45), "004");
		Set<Student> stu=hm.keySet();
		for(Student s:stu){
			String age=hm.get(s);
			System.out.println("键--姓名:"+s.getName()+"--"+"年龄:"+s.getAge()+"------"+"值:"+age);
		}	
	}
}
package day30.test1;

public class Student {
private String name;
private int age;
public Student() {
	super();
}
public Student(String name, int age) {
	super();
	this.name = name;
	this.age = 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 int hashCode() {
		return this.name.hashCode()+this.age;
	}
	public boolean equals(Object obj) {
		if (this==obj) {
			return true;
		}
		if (!(obj instanceof Student)) {
			return false;
		}
		Student s=(Student)obj;
		if (this.name.equals(s.getName())&&this.age==s.getAge()) {
			return true;
		}
		return false;
	}

}
运行结果:

     3、HashMap和Hashtable的区别:
           a、Hashtable线程安全,效率低;不允许null键和值
           b、HashMap线程不安全,效率高;允许null键和值
    4、示例:统计字符串中每一个字符出现的次数
import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo {
	public static void main(String[] args) {
		TreeMap<Character, Integer> tree = new TreeMap<Character, Integer>();
		String s = "cbxzbvavdvgd";
		char[] ch = s.toCharArray();
		for (Character ch2 : ch) {
			Integer in = tree.get(ch2);
			if (in == null) {
				tree.put(ch2, 1);
			} else {
				tree.put(ch2, ++in);
			}
		}
		System.out.println(tree);
		Set<Character> ter = tree.keySet();
		StringBuilder sb = new StringBuilder();
		for (Character ara : ter) {
			Integer rr = tree.get(ara);
			sb.append(ara).append("(").append(rr).append(")");
		}
		String ww = sb.toString();
		System.out.println(ww);
	}
}
运行结果:

    5、Properties:
    (1)Properties:是一个表示属性集的集合。可以从流中加载数据或者把数据保存到流中。键和值都是字符串。 是唯一一个可以和IO流结合使用的集合类。Properties的父亲是Hashtable。
    (2)Properties作为集合的特殊功能:
        a、修改功能:
             public Object setProperty(String key,String value):如果该键不存在,就存该键值对,返回null;如果该键存在,就用新值来替换旧值,并将旧的值返回
        b、获取功能:
             ①、public String getProperty(String key):根据键,获取其对应的值,如果该键不存在,返回null
             ②、public String getProperty(String key,String defaultValue):根据键,获取其对应的值,如果该键不存在,返回给定的默认值defaultValue,如果存在,返回其对应的值。
             ③、public Set<String> stringPropertyNames():获取该集合对象的键的集合
        c、Properties作为和IO流结合使用的集合的特殊功能:
             ①、public void list(PrintStream out):把集合中的数据按照键值对的形式存储到文本文件中。
             ②、public void list(PrintWriter out):把集合中的数据按照键值对的形式存储到文本文件中。
             ③、public void load(InputStream inStream):从文本文件中把数据加载到集合中。
             ④、public void load(Reader reader):从文本文件中把数据加载到集合中。
                     注意:  对文本文件是有要求的,要求数据必须是键值对形式。
             ⑤、public void store(OutputStream out,String comments):把集合中的数据保存到文本文件中。
             ⑥、public void store(Writer writer,String comments):把集合中的数据保存到文本文件中。
                     注意:store和list方法的区别 list的参数值能是PrintWriter或PrintStream而store的参数是PrintStream或者Writer
    (2)案例:请查找文件user.txt中是否有lisi这个键,如果有,则修改其值为50:
              user.ext内容:
                         zhangsan=10;
                         lisi=20
                         linqingxia=26;
import java.io.*;
import java.util.*;

/*
 * 需求:请查找文件user.txt中是否有lisi这个键,如果有,则修改其值为50
 * 
 * 思路:
 * 		A:把文本文件的数据加载到集合中
 * 		B:遍历集合,获取到每一个键
 * 		C:判断该键是否是lisi,如果是则修改值
 * 		D:把集合中的数据重新保存到文本文件中
 */
public class PropertiesTest {
	public static void main(String[] args) throws IOException {
		method1();
	}

	private static void method1() throws IOException {
		Properties prop = new Properties();

		// 把文本文件的数据加载到集合中
		FileReader reader = new FileReader("user.txt");
		prop.load(reader);
		reader.close();
		System.out.println(prop);
		System.out.println("----------------");

		// 遍历集合,获取到每一个键
		Set<String> set = prop.stringPropertyNames();
		for (String key : set) {
			if ("lisi".equals(key)) {
				prop.setProperty(key, "50");
			}
		}
		System.out.println(prop);
		System.out.println("-------------------");
		// 把集合中的数据重新保存到文本文件中
		BufferedWriter bw = new BufferedWriter(new FileWriter("user.txt"));
		prop.store(bw, "中国");
		// 输出user.txt文件中的内容
		BufferedReader br = new BufferedReader(new FileReader("user.txt"));
		String string = null;
		while ((string = br.readLine()) != null) {
			System.out.println(string);
		}
		bw.close();
		br.close();
	}
}
运行结果:


             









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值