1.HashMap
线程不安全,允许存放null值,保证键唯一。
2.TreeMap
保证键唯一的基础上进行升序排序。
package gather;
import java.util.HashMap;
import java.util.TreeMap;
public class HAndT {
public static void main(String[] args) {
HashMap<Integer, String> hm = new HashMap<Integer,String>();
hm.put(6, "you");
hm.put(1, "are");
hm.put(6, "i");
hm.put(2, "best!");
hm.put(3, "best!");
System.out.println(hm);
TreeMap<Integer, String> hm2 = new TreeMap<Integer,String>();
hm2.put(6, "you");
hm2.put(1, "are");
hm2.put(6, "i");
hm2.put(2, "best!");
System.out.println(hm2);
}
}
3.Map集合的两种遍历
- 将值存入Collection集合,只能遍历值,无法遍历键
- 将键存入Set集合,遍历出键后,可以通过get方法获取对应的值
package gather;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/*
* 在当前行前插入一行快捷键为:ctrl+shift+enter
* 在当前行后插入一行快捷键为:shift+enter
*/
public class MapErgodic {
public static void main(String[] args) {
/*
* 将值存入Collection集合,只能遍历值,无法遍历键
*/
Map<Integer, String> m1 = new HashMap<Integer,String>();
m1.put(2, "a");
m1.put(1, "b");
m1.put(2, "c");
m1.put(24, "d");
m1.put(10, "e");
Collection<String> col=m1.values();//将Map集合的值存入Collection中
Iterator<String> iter=col.iterator();//放入迭代器
while (iter.hasNext()) {//判断是否有下一个值
String value = iter.next();
System.out.println(value+" ");
}
/*
* 将键存入Set集合,遍历出键后,可以通过get方法获取对应的值
*/
Set<Integer> se=m1.keySet();//将键存入Set集合中
Iterator<Integer> iter2 = se.iterator();
while (iter2.hasNext()) {
Integer key = iter2.next();//获取set集合中存取的键
String value = m1.get(key);//通过get获取对应的值
System.out.println(key+","+value);
}
}
}
4.Map集合的应用
****** 统计每个字符出现的次数 ******
package gather;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Count {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
System.out.print("请输入一个字符串:");//a c c c s s
String str = s.next();
char[] ch = str.toCharArray();//把字符串拆分成字符数组
Map<Character, Integer> m = new HashMap<Character,Integer>();
for (int i = 0; i < ch.length; i++) {
int a=1;
if (m.containsKey(ch[i])) {//判断字符串是否在集合中,contains:包含
a=m.get(ch[i])+1;//获取集合的次数然后加1
}
m.put(ch[i], a);//a,1 c,1 c,2 c,3
}
Set<Character> set = m.keySet();//将键存入set集合中
Iterator<Character> iter = set.iterator();
while (iter.hasNext()) {
Character key = iter.next();
int value = m.get(key);
System.out.println("字符"+key+"出现了"+value+"次");
}
}
}