java util Map
5:Map接口
键值对方式存储元素。
V put(K key, V value) : 放元素
V get(Object key) : 取元素
size():得到长度
Set keySet() :得到所有的键的集合
Map实现类:
HashMap: 不保证排序、非线程安全
TreeMap: 可以实现排序,不是线程安全的
Set<Map.Entry<K,V>> entrySet() :
public class MapDemo {
public static void main(String[] args) {
//
Map<String,Student> map=new HashMap<>();
//添加元素
map.put("1001", new Student("张三",80,"1001"));
map.put("1002", new Student("李四",88,"1002"));
map.put("1003", new Student("王五",60,"1003"));
map.put("1004", new Student("麻六",88,"1004"));
//取元素
Student s=map.get("1004");
System.out.println(s.getId());
System.out.println(s.getName());
System.out.println(map.size());
System.out.println(map.containsKey("1003"));//是否包含某个键
//根据key删除某个对象
map.remove("1001");
System.out.println(map);
//遍历Map
//得到key集合
Set<String> keys=map.keySet();
for (String key : keys) {
System.out.println("key:"+key);
Student ss=map.get(key);
System.out.println(ss.getName());
System.out.println(ss.getId());
System.out.println("-------------------------------------");
}
System.out.println("============================================================");
//遍历方式二:
Set<Entry<String, Student>> ents=map.entrySet();
for (Entry<String, Student> e : ents) {
System.out.println("key:"+e.getKey());
Student ss=e.getValue();
System.out.println(ss.getName());
System.out.println(ss.getId());
System.out.println("-------------------------------------");
}
System.out.println(map.isEmpty());
System.out.println(map.values());
//清除所有
map.clear();
System.out.println(map);
}
}
Map排序
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class MapDemo2 {
public static void main(String[] args) {
Map<String, Student> map = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);//降序
}
});
// 添加元素
map.put("1001", new Student("张三", 80, "1001"));
map.put("1002", new Student("李四", 88, "1002"));
map.put("1003", new Student("王五", 60, "1003"));
map.put("1004", new Student("麻六", 88, "1004"));
System.out.println(map);
}
}
6:创建线程安全集合
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
//创建线程安全的集合
List<String> lst=Collections.synchronizedList(new ArrayList<>());
Map<String,String> map=Collections.synchronizedMap(new HashMap<>());
Set<String> set=Collections.synchronizedSet(new HashSet<>());
}
}