Map 和 Set
1.模型
Map:key-value以键值对的方式存储。key值必须不同,value值可以相同。
Set:数学上的集合,里面的元素不能重复。
2.Map的使用
2.1Map的常见方法
Map的方法:
V put(K key, V value)
- 添加,根据key值存放对应的value值。
根据给定的key来生成对应的哈希函数
K类型的key,V类型的value;若添加的key已经存在,则会将之前的value覆盖。
V get(Object key)
- 返回key对应的value值
V getOrDefault(Object key, V defaultValue)
- 返回 key 对应的 value,key 不存在,返回默认值
V remove(Object key)
- 删除 key 对应的映射关系
Set<K> keySet()
- 将所有key转变为一个Set集合返回,不可重复
Collection<V> values()
- 将所有value值转变为Collection集合返回,可重复
Set<Map.Entry<K, V>> entrySet()
- 返回所有的Key-value映射关系
boolean containsKey(Object key)
- 判断是否包含key
boolean containsValue(Object value)
- 判断是否包含value
Map的方法示例
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<>();
//最后放入的重复的key会将之前的覆盖,例如这里只会保存key 1- value"ww"
map.put(1,"yy");
map.put(1,"ww");
map.put(2,"cc");
//Map每次put时根据key值存放,
String str = map.get(2);
System.out.println(str);
str = map.getOrDefault(80,"c");
System.out.println(str);
// 返回 key 对应的 value,key 不存在,返回默认值
map.remove(1);
//删除 key 对应的映射关系
System.out.println(map);
Set<Integer> set = map.keySet();
System.out.println(set);
Collection<String> collection = map.values();
System.out.println(collection);
//返回所有key-value的映射关系
Set<Map.Entry<Integer,String>> set1 = map.entrySet();
System.out.println(set1);
//判断是否包含key值
boolean flg = map.containsKey(2);
System.out.println(flg);
//遍历Map集合
for (Map.Entry<Integer, String> entry :
map.entrySet()) {
System.out.println(entry.getKey()+ " " + entry.getValue());
}
}
3. Set的使用
3.1 Set的常见方法
boolean add(E e)
- 添加元素,重复元素不会被添加成功,即Set集合中的元素不能重复
void clear()
- 清空集合
boolean contains(Object o)
- 判断o是否在集合中
Iterator<E> iterator()
- 返回迭代器,使用迭代器来遍历Set集合。
能否使用迭代器,取决于是否实现了Iterable接口。
boolean remove(Object o)
- 删除集合中的o
Set的方法示例
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("ww");
set.add("qq");
set.add("cc");//无序的
System.out.println(set);//打印结果:[ww, qq, cc]
//迭代器遍历set
//可以使用迭代器,是否实现了Iterable接口
Iterator it = set.iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");//遍历结果:ww qq cc
}
System.out.println();
boolean flg = set.contains("ww");
System.out.println(flg); //打印结果:true
set.remove("cc");
System.out.println(set);//打印结果:[ww, qq]
set.clear();
System.out.println(set);//打印结果:[]
}