集合Set
继承自collection,没有自己新增的方法。不支持随机访问,不能存放重复元素。
java
Set<String> set = new HashSet<>();
set.add("hhxl");
set.add("hhxl");
System.out.println(set);

同样移除数据的时候,也不能够根据下标,只能是元素,比如:
java
set.remove("hhxl");
底层使用的是哈希表存放元素,不能确定顺序。
java
Set<String> set = new HashSet<>();
set.add("hxl");
set.add("lhw");
set.add("520");
System.out.println(set);

为了维护插入顺序,有LinkedHashSet结构,相当于在哈希表的基础上多了一个Link数据结构,每一个元素还会有指向下一个元素。比如:
java
Set<String> set = new LinkedHashSet<>();
set.add("hxl");
set.add("lhw");
set.add("520");
System.out.println(set);

还有一种set是TreeSet,可以对元素 进行排序;
java
Set<String> set = new TreeSet<>();
set.add("2");
set.add("8");
set.add("1");
System.out.println(set);

Map映射
Map是一个新的类,并没有继承某个类。
size()集合里面的键值对数量
isEmpty()映射里面是不是空的
containsKey(key)里面传入键,判断是否包含某个键
get(key)里面传入键得到其相应的映射值
put(key, value)存储键值对
remove()传入键,移除相应的键值对
clear()清空所有的键值对
putAll()里传入另外一个Map,将其所有的键值对插入
keySet()以集合形式返回里面存放的所有键
values()返回所有的值的集合
entrySet()返回所有的键值对
Entry() 表示一个键值对
尝试一下:
java
Map<Integer, String> map = new HashMap<>();
map.put(1,"hxl");
map.put(2,"lhw");
System.out.println(map);

java
System.out.println(map.get(2));

HashMap和集合一样,不允许出现重复的键。value可以重复。
为了在插入的时候不被覆盖,有一个putIfAbsent()方法,当传入的键重复就不会插入。比如:
java
Map<Integer, String> map = new HashMap<>();
map.put(1,"hxl");
map.put(2,"lhw");
map.putIfAbsent(2,"520");
System.out.println(map);

如果只是单纯的使用
java
Map<Integer, String> map = new HashMap<>();
map.put(1,"hxl");
map.put(2,"lhw");
map.put(2,"520");
System.out.println(map);
就会输出覆盖后的结果:

此外,还有一个取值的方法 getOrDefault,如果键不存在就会返回备选的输出:
java
Map<Integer, String> map = new HashMap<>();
map.put(1,"hxl");
map.put(2,"lhw");
map.put(3,"520");
System.out.println(map.getOrDefault(0,"1314"));

同样,存储的顺序也是不一样的
java
Map<String, String> map = new HashMap<>();
map.put("h","hxl");
map.put("l","lhw");
map.put("5","520");
System.out.println(map);
System.out.println(map.keySet());
System.out.println(map.values());

之前我们说到会被覆盖的情况,如果被覆盖会返回之前的值,否则返回null。比如:
java
map.put("5","520");
System.out.println(map.put("5","1314"));

java
System.out.println(map.put("1","1314"));

还有replace方法,感觉和put方法是等效的。不过必须里面有相应的键才会进行覆盖(替换value)
java
map.replace("5","1314")
此外,null也可以作为键/值。
java
map.put("h",null);
map.put(null,"lhw");
compute方法用于计算后修改value,比如希望某个value在原先的基础上变化:
java
Map<Integer, String> map = new HashMap<>();
map.put(0,"hxl");
map.put(1,"lhw");
map.compute(0,(key, value)-> value + "5201314");
System.out.println(map);

相应的还有computeIfPresent,如果存在才会进行修改,否则不会在映射里面发生任何变化
java
Map<Integer, String> map = new HashMap<>();
map.put(0,"hxl");
map.put(1,"lhw");
map.computeIfPresent(2,(_,value)-> "5201314");
System.out.println(map);

以及computeIfAbsent,只有不存在的时候才会进行覆盖:
java
Map<Integer, String> map = new HashMap<>();
map.put(0,"hxl");
map.put(1,"lhw");
map.computeIfAbsent(2,(key)-> "5201314");
System.out.println(map);

merge方法,有一个独特的参数传入,有旧值有新值
java
map.put(1,"lhw");
map.merge(1,"520",(old, value)->value+old);
System.out.println(map);
