1. 程式人生 > 實用技巧 >Java Map

Java Map

1. map

package com.qf.demo03;

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

public class Test1Map {

	public static void main(String[] args) {
		/*
		 * Map,操作是鍵值對,成對的物件。
		 * key和value必須是一一對應的。
		 * key不能重複
		 */
		Map<String, String> map = new HashMap<>();
		/*
		 * 1.put(key,value)-->value
		 * 
		 * 將制定的引數鍵值對,存入map集合中。
		 * 儲存的key不允許重複,如果重複,會覆蓋原來的value值。
		 * 返回值是被替換的value。如果key不重複,就返回null
		 */
		String s1 = map.put("A", "aaa");
		String s2 = map.put("B", "bbb");
		String s3 = map.put("C", "ccc");
		String s4 = map.put("D", "ddd");
		System.out.println(map);//{A=aaa, B=bbb, C=ccc, D=ddd}
		System.out.println(s1+","+s2+","+s3+","+s4);//null,null,null,null
		String s5 = map.put("D", "XXX");
		System.out.println(map);//{A=aaa, B=bbb, C=ccc, D=XXX}
		System.out.println(s5);//ddd
		
		//2.clear(),清空map集合,就是刪除所有的鍵值對
//		map.clear();
//		System.out.println(map);
		
		
		//3.containsKey(key)-->boolean,是否包含指定的key
		System.out.println(map.containsKey("D"));
		//4.containsValue(value)-->boolean,是否包含指定的value
		System.out.println(map.containsValue("ddd"));
		
		/*
		 * 5.get(key)-->value
		 * 根據key,獲取它所對應的value值。
		 * 如果key不存在,返回null
		 */
		System.out.println(map.get("D"));//XXX
		System.out.println(map.get("DD"));//null
		
		if(map.containsKey("DD")){
			System.out.println(map.get("DD"));
		}else{
			System.out.println("map中查無此資料。。");
		}
		
		/*
		 * 6.remove(key)->value
		 * 從map中,根據指定的key,移出該鍵值對。返回值是被刪除的value
		 * 如果map中沒有這個key,返回值就是null。
		 */
		String s6 = map.remove("DD");
		System.out.println(map); //{A=aaa, B=bbb, C=ccc}
		System.out.println(s6); //XXX
		
		System.out.println(map.size());//4,獲取map集合中,鍵值對的數量
	}

}

2. hashmap實現類

package com.qf.demo03;

import java.util.HashMap;
import java.util.HashSet;

public class Test3HashMap {

	public static void main(String[] args) {
		//1.建立Map集合,key:整數,value:人物件
		//key一定是去重的。
		
		HashMap<Integer, Person> map1 = new HashMap<Integer, Person>();
		map1.put(1, new Person("張三", 20));
		map1.put(2, new Person("李四", 25));
		map1.put(3, new Person("王五", 28));
		System.out.println(map1);
		map1.put(1, new Person("趙六", 40));
		System.out.println(map1);
		
		
		HashMap<Person, String> map2 = new HashMap<>();
		/*
		 * hashMap的key,如何去重?同hashSet去重原理相同。
		 * 底層自動呼叫hashCode和equals()
		 * 
		 * hashCode:
		 * 	相同的物件,雜湊值必須相同
		 * 	不同的物件,雜湊值儘量不同
		 * 
		 * equals:
		 * 	相同的物件:必須true
		 * 	不同的物件:必須false
		 */
		map2.put(new Person("王二狗", 30), "矮矬窮");
		map2.put(new Person("李小花", 28), "美美噠");
		map2.put(new Person("王二狗", 30), "高富帥");
		System.out.println(map2.size());
		System.out.println(map2);
		
		HashSet<String> set = new HashSet<>();
		set.add("aaa");
		
	}

}

3. treemap

package com.qf.demo03;

import java.util.HashMap;
import java.util.HashSet;

public class Test3HashMap {

	public static void main(String[] args) {
		//1.建立Map集合,key:整數,value:人物件
		//key一定是去重的。
		
		HashMap<Integer, Person> map1 = new HashMap<Integer, Person>();
		map1.put(1, new Person("張三", 20));
		map1.put(2, new Person("李四", 25));
		map1.put(3, new Person("王五", 28));
		System.out.println(map1);
		map1.put(1, new Person("趙六", 40));
		System.out.println(map1);
		
		
		HashMap<Person, String> map2 = new HashMap<>();
		/*
		 * hashMap的key,如何去重?同hashSet去重原理相同。
		 * 底層自動呼叫hashCode和equals()
		 * 
		 * hashCode:
		 * 	相同的物件,雜湊值必須相同
		 * 	不同的物件,雜湊值儘量不同
		 * 
		 * equals:
		 * 	相同的物件:必須true
		 * 	不同的物件:必須false
		 */
		map2.put(new Person("王二狗", 30), "矮矬窮");
		map2.put(new Person("李小花", 28), "美美噠");
		map2.put(new Person("王二狗", 30), "高富帥");
		System.out.println(map2.size());
		System.out.println(map2);
		
		HashSet<String> set = new HashSet<>();
		set.add("aaa");
		
	}

}

  

package com.qf.demo03;

import java.util.Map;
import java.util.TreeMap;

public class Test4TreeMap {

	public static void main(String[] args) {
		Map<Integer, String> map1 = new TreeMap<>();
		map1.put(1, "面朝大海,春暖花開");
		map1.put(3, "你說的都對");
		map1.put(2, "Jerry愛大米");
		System.out.println(map1);
		
		
		map1.put(3, "床前明月光");
		System.out.println(map1);
		
		Map<String, String> map2 = new TreeMap<>();
		map2.put("C", "地上鞋三雙");
		map2.put("B", "舉頭望明月");
		map2.put("A", "疑是地上霜");
		System.out.println(map2);
	}

}

4. 使用comparator比較器

package com.qf.demo03;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

class Student{
	private String name;
	private int age;
	private int score;
	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 getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(String name, int age, int score) {
		super();
		this.name = name;
		this.age = age;
		this.score = score;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
	}
	
}
public class Test6TreeMap {

	public static void main(String[] args) {
		//題目:將Student物件,存入到Map中,作為key,value:【優秀,良好,中等,及格,不及格】
		/*
		 * new TreeSet()-->Comparable
		 * new TreeSet(Comparator)-->Comparator
		 * 
		 * new TreeMap()-->Comparable
		 * new TreeMap(Comparator)-->Comparator
		 */
		
		
		TreeMap<Student, String> map  =new TreeMap<>(new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				//1.成績:從高到低
				if(o1.getScore()>o2.getScore()){
					return -1;
				}else if(o1.getScore()<o2.getScore()){
					return 1;
				}else{
					//2.年齡:從小到大
					if(o1.getAge() < o2.getAge()){
						return -1;
					}else if(o1.getAge() > o2.getAge()){
						return 1;
					}else{
						//3.姓名
						return o1.getName().compareTo(o2.getName());
					}
				}
			}
		});
		map.put(new Student("王二狗", 18, 88), "良好");
		map.put(new Student("李小花", 17, 98), "優秀");
		map.put(new Student("Rose", 17, 88), "良好");
		map.put(new Student("李鐵柱", 18, 88), "良好");
		
//		Set<Student> keySet = map.keySet();
//		Iterator<Student> it2 = keySet.iterator();
		
		
		Iterator<Student> it = map.keySet().iterator();
		while(it.hasNext()){
			Student student = it.next();
			System.out.println(student+"\t"+map.get(student));
		}
		
		
	}

}

5. map.entry

package com.qf.demo01;

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

public class Test1Entry {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("A", "aaa");
		map.put("B", "bbb");
		map.put("C", "ccc");
		map.put("D", "ddd");
		/*
		 * map中儲存了4個鍵值對:
		 * 
		 * 4個鍵值對——>4個Entry物件
		 * 
		 * map:
		 * 	key-->value
		 * 	key-->value
		 * 	key-->value
		 * 	...
		 * 
		 * Set:
		 * 	entry:key,value
		 * 	entry:key,value
		 * 	entry:key,value
		 * 	....
		 * 
		 * 獲取map中的每一個元素:迭代map集合?
		 * 1.map中的所有的key,儲存到一個Set中
		 * 		A:keySet()--->Set集合
		 * 		B:iterator()-->迭代獲取每一個key
		 * 		C:根據key獲取map中對應的value
		 * 
		 * 2.map中的鍵值對組合entry,儲存到一個Set中
		 * 		A:entrySet()--->Set集合
		 * 		B:iterator()-->迭代獲取每一個entry
		 * 		C:根據entry物件,獲取裡面的key和value
		 * 
		 * 
		 * 
		 * 注意點:
		 * iterator()--->Collection介面
		 * 		List,Set。。。ArrayList,linkedList,HashSet,TreeSet....
		 * 
		 * map是沒有迭代器
		 */
		//step1:獲取map集合對應set:entry
		Set<Entry<String, String>> entrySet = map.entrySet();
		
		//step2:操作set集合,獲取迭代器物件
		Iterator<Entry<String, String>> it = entrySet.iterator();
		//step3:迴圈遍歷迭代
		while(it.hasNext()){
			//呼叫next(),獲取Set集合中物件:entry
			Entry<String, String> entry = it.next();
			//step4:操作entry,獲取key和value
			System.out.println(entry.getKey()+"\t"+entry.getValue());
		}
		
		System.out.println("--------------");
		/*
		 * for(資料型別 變數名:陣列/集合){
		 * }
		 */
		for(Entry<String,String> entry:map.entrySet()){//集合Set<Entry>
			System.out.println(entry.getKey()+"\t"+entry.getValue());
		}
		
		
		for(String key:map.keySet()){//集合Set<Key>
			System.out.println(key+"\t"+map.get(key));
		}
	}

}

6. linkedhashmap

  

package com.qf.demo01;

import java.util.HashMap;
import java.util.LinkedHashMap;

public class Test2LinkedHashMap {

	public static void main(String[] args) {
		/*
		 * LinkedHashMap集合
		 * 記錄了儲存的順序。
		 */
		
		HashMap<String, String> map = new HashMap<>();
		map.put("ddd", "ddd");
		map.put("aaa", "aaa");
		map.put("ccc", "ccc");
		map.put("bbb", "bbb");
		System.out.println(map);
		
		
		LinkedHashMap<String, String> map2 = new LinkedHashMap<>();
		map2.put("D", "ddd");
		map2.put("A", "aaa");
		map2.put("C", "ccc");
		map2.put("B", "bbb");
		System.out.println(map2);
	}

}

7. hashtale

package com.qf.demo02;

import java.util.HashMap;
import java.util.Hashtable;

public class Test3HashTable {

	public static void main(String[] args) {
		/*
		 * HashMap,支援null
		 * 
		 * HashTable,不支援null,丟擲異常:NullPointerException
		 */
		HashMap<String, String> map = new HashMap<>();
		map.put("A", "aaa");
		map.put("B", "bbb");
		map.put("C", null);//null物件
		map.put("D", null);
		System.out.println(map);
		map.put(null, "haha");
		System.out.println(map);
		map.put(null, "hehe");
		System.out.println(map);
		
		
		Hashtable<String, String> table = new Hashtable<>();
		table.put("AA", "aaa");
		table.put("BB", "bbb");
//		table.put("CC", null);
		table.put(null, "ddd");
		System.out.println(table);
		
	}

}

8. proparties

package com.qf.demo03;

import java.util.Properties;

public class Test4Properties {

	public static void main(String[] args) {
		/*
		 * Map
		 * HashTable
		 * Properties
		 * 看系統的配置資訊:演示效果
		 * 
		 * 
		 * Scanner scan = new Scanner(System.in);
		 * System.out.println();
		 */
		//1.通過System類,獲取系統的一些屬性資訊,在Properties集合中
		Properties properties = System.getProperties();
//		System.out.println(properties);
		//2.顯示到螢幕上
		properties.list(System.out);//System.out-->PrintStrem(列印流),屬於IO範疇的,現在超綱
	}

}

  

package com.qf.demo03;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Properties;

public class Test5Properties {

	public static void main(String[] args) throws Exception {
		//預設泛型:String型別
		Properties properties = new Properties();
		//向集合中儲存一些屬性資訊
		System.out.println(properties);
//		properties.put("name", "zhangsan");
		properties.setProperty("username", "zhangsan");//使用者名稱這個屬性
		properties.setProperty("password", "123456");
		System.out.println(properties);
		/*
		 * 支援持久化儲存:
		 * 		瞬時儲存:記憶體中,儲存的資料,都叫瞬時資料。當程式結束的時候,物件,變數,常量。。。從記憶體中銷燬,釋放記憶體。
		 * 		持久儲存:程式關閉,電腦關機等,資料還在。資料庫,本地檔案。
		 */
		
		//將Properties中的屬性資訊持久化儲存——>儲存到檔案。
		//從此行開始,程式碼超綱:聽思路,程式碼看懂註釋
		
		//step1.建立一個檔案物件File類的物件,表示C盤Ruby目錄下的message.properties檔案
		File file = new File("C:\\Ruby\\message.properties");
		
		//step2:建立檔案輸出流,用於將資料寫入到file檔案中
		FileOutputStream fos = new FileOutputStream(file);
		
		//step3:將properties裡面的屬性資訊,儲存到file檔案裡
		properties.store(fos, "mymessage");
		System.out.println("資訊儲存完畢。。。");
	}

}

  

package com.qf.demo03;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class Test6Properties {

	public static void main(String[] args) throws Exception {
		//1.step1:建立檔案物件,表示儲存了資料的本地檔案:C盤Ruby資料夾,message.properties
		File file = new File("C:\\Ruby\\message.properties");
		
		//2.建立集合Properties,用於儲存從檔案中讀來的資料
		Properties properties2 = new Properties();
		System.out.println(properties2);//{}
		
		
		//3.從檔案上建立輸入流,用於讀取檔案中的資料
		FileInputStream fis = new FileInputStream(file);
		
		//4.將file中的資料,到properties集合中
		properties2.load(fis);
		
		System.out.println(properties2);
	}

}

9. 泛型安全

package com.qf.demo04;

import java.util.ArrayList;
import java.util.List;

class Point1{
	private int x;
	private int y;
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
}
class Point2{
	private double x;
	private double y;
	public double getX() {
		return x;
	}
	public void setX(double x) {
		this.x = x;
	}
	public double getY() {
		return y;
	}
	public void setY(double y) {
		this.y = y;
	}
}
class Point3{
	private String x;
	private String y;
	public String getX() {
		return x;
	}
	public void setX(String x) {
		this.x = x;
	}
	public String getY() {
		return y;
	}
	public void setY(String y) {
		this.y = y;
	}
}
//1.泛型作用在類上,當建立該類物件的時候,決定這個泛型
class Point<T>{//type
	private T x;//宣告一個屬性,屬性名x,屬性型別T
	private T y;//晟敏一個屬性,屬性名y,屬性型別T
	
	//get和set方法。。
	public void setX(T x){//2.用於普通的方法
		this.x = x;
	}
	
	public void setY(T y){
		this.y = y;
	}
	
	public T getX(){
		return x;
	}
	public T getY(){
		return y;
	}
	
	//3.<M>,靜態方法上自己獨立宣告泛型,不能使用類的。
	public static <M> M test(M m){
		System.out.println(m);
		return m;
	}
	
}
public class Test7Generics {
	
	
	
	

	public static void main(String[] args) {
		//描述一個點:x軸,y軸
		
//		Point1 p1 = new Point1();
//		p1.setX(1);//int
//		p1.setY(2);//int
//		System.out.println(p1.getX()+"\t"+p1.getY());
//		
//		Point2 p2 = new Point2();
//		p2.setX(1.34);//double
//		p2.setY(4.21);//double
//		System.out.println(p2.getX()+"\t"+p2.getY());
//		
//		Point3 p3 = new Point3();
//		p3.setX("北緯108");//String
//		p3.setY("東經89");//String
//		System.out.println(p3.getX()+"\t"+p3.getY());
		/*
		 * 作用在類上的泛型,給物件用的,凡是物件的屬性和方法,都可以直接使用這個泛型。
		 * 該泛型,隨著物件的建立而確定。
		 */
		Point<Integer> p1 = new Point<>();//x,y兩個屬性
		p1.setX(1);//int-->Integer
		p1.setY(2);
		
		System.out.println(p1.getX()+"\t"+p1.getY());
		
		Point<Double> p2 = new Point<>();
		p2.setX(3.14);
		p2.setY(4.56);
		System.out.println(p2.getX()+"\t"+p2.getY());
		
		Point<String> p3 = new Point<>();
		p3.setX("北緯108");
		p3.setY("東經89");
		
		List<String> list1 = new ArrayList<String>();
		List<Integer> list2 = new ArrayList<>();
		
		//泛型的擦除:定義類有泛型,但是建立物件的時候沒有指明泛型。該型別就是Object型別了
		List list3 = new ArrayList<>();
//		list3.add(Object);
		
		Point p4 = new Point();//泛型被擦除,沒有具體的型別了,——>Object型別
		
		
		String s1 = Point.test("abc");//M-->String
		Integer i1 = Point.test(100);//M-->Integer
	}

}

  

package com.qf.demo04;

import java.util.ArrayList;
import java.util.List;
class Person{
	
}

class Student extends Person{
	
}
public class Test8Generics {
	/*
	 * 該方法,列印一個list集合
	 * ?代表了該方法的引數為List裡儲存任意型別的資料
	 * List<Person>
	 * List<Student>
	 * List<String>
	 * List<Object>
	 */
	public static void printList(List<?> list){
		
	}
	//該方法只能接受List<Object> 
	public static void test(List<Object> list){
		
	}
	/*
	 * ? extends Person:限定了上限
	 * 接受集合的泛型是Person。或者是Person的子類型別。
	 * List<Person>
	 * List<Student>
	 */
	public static void test2(List<? extends Person> list){
		
	}
	/*
	 * ? super Student:限定了下限
	 * 接收集合的泛型是Student,以及Student的父類型別
	 * List<Student>
	 * List<Person>
	 * List<Object>
	 */
	public static void test3(List<? super Student> list){
		
	}
	public static void main(String[] args) {
		List<Person> l1 = new ArrayList<>();
		l1.add(new Person());
		l1.add(new Student());//Student-->Person
		
		List<Student> l2 = new ArrayList<>();
		l2.add(new Student());
		
		List<String> l3 = new ArrayList<>();
		l3.add("haha");
		l3.add("hehe");
		
		List<Object> l4 = new ArrayList<>();
		l4.add(new Object());//Object
		l4.add(new Person());//Person-->Object
		l4.add(new Student());//Student-->Object
		l4.add("abc");//String-->Object
		
		printList(l1);
		printList(l2);
		
//		test2(l2);
		test3(l1);
		test3(l2);
		test3(l4);
		/*
		 * 注意點:
		 * 	Student繼承Person類
		 * 	List<Student> 不是List<Person>的子類
		 */
		
		
	}

}

10.Collections

package com.qf.demo05;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Person implements Comparable<Person>{
	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 Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	@Override
	public int compareTo(Person o) {
		// TODO Auto-generated method stub
		return 0;
	}
	
}
public class Test9Collections {
	public static void main(String[] args) {
		List<String> l1 = new ArrayList<String>();
		l1.add("abc");
		l1.add("ccc");//add方法每次只能新增一個元素。
		/*
		 * 1、Collections.addAll(容器,要新增的元素)
		 * 向容器中同時新增多個元素物件
		 */
		Collections.addAll(l1, "hello","world","haha","hehe");
		System.out.println(l1);
		
		ArrayList<String> l2 = new ArrayList<>();//執行緒不安全
		
		/*
		 * synchronizedList(集合)-->集合
		 * synchronizedSet()
		 * synchronizedMap()...
		 * 引數是執行緒不安全的集合,返回值執行緒安全的集合。
		 */
		List<String> newL2 = Collections.synchronizedList(l2);
		
		/*
		 * List集合:有序,儲存順序。有下標
		 * 排序:將list集合中的元素進行排序。
		 * 類比陣列排序
		 * 
		 * int[] arr = {1,7,4,6,2,5}
		 * 排序:冒泡,選擇,Arrays.sort()
		 */
		List<Integer> l3 = new ArrayList<>();
		Collections.addAll(l3, 1,7,4,6,2,5);
		System.out.println(l3);
		
		//list->sort,排序,排序規則
		Collections.sort(l3);
		System.out.println(l3);
		
		List<Person> l4 = new ArrayList<>();
		l4.add(new Person("王二狗", 18));
		l4.add(new Person("李小花", 17));
		l4.add(new Person("李鐵柱", 19));
		System.out.println(l4);
		
		Collections.sort(l4);//使用的是預設的比較器:Comparable
		
		Collections.sort(l4, new Comparator<Person>() {//使用的自定義的比較器:Comparator

			@Override
			public int compare(Person o1, Person o2) {
				return 0;
			}
		});
		
	}
}