1. Map
1.1 特点:无序、以键值对的形式添加元素,键不能重复,值可以重复
它没有继承Collection接口
public static void main(String[] args) {
// Collection接口集合框架中的顶级接口,是jset和list的父接口,不是map的父接口
// map
// 1,特点,无序,以键值对的储存数据
Map<String, Object> map = new Hashtable<>();
map.put("name", "zs");
map.put("sex", "boy");
map.put("age", 21);
// 问题,当个键值相同时,值会如何?
// 答案:当键值相同时,值被覆盖!!!
map.put("name", "ww");
map.put("score", 21);
System.out.println(map);
// 2.遍历
// 1)获取所有的建
System.out.println("----------------------1获取所有的建keys------------------)");
Set<String> keys = map.keySet();
for (String k : keys) {
System.out.println(k);
}
// 2)获取所有的值values
System.out.println("------2)获取所有的值values---------");
Collection<Object> values = map.values();
for (Object obj : values) {
System.out.println(obj);
}
// 3)获取所有的建值
System.out.println("-------3)获取所有的建值-----------------");
Set<Entry<String, Object>> entrySet = map.entrySet();
for (Entry<String, Object> entry : entrySet) {
System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
;
}
entrySet.forEach(e -> {
System.out.println(e.getKey() + "=" + e.getValue());
});
}
}
1.2 遍历
1.2.1 先取出保存所有键的Set,再遍历Set即可(2种)
1.2.2 先取出保存所有Entry的Set,再遍历此Set即可
// 2.遍历
// 1)获取所有的建
System.out.println("----------------------1获取所有的建keys------------------)");
Set<String> keys = map.keySet();
for (String k : keys) {
System.out.println(k);
}
// 2)获取所有的值values
System.out.println("------2)获取所有的值values---------");
Collection<Object> values = map.values();
for (Object obj : values) {
System.out.println(obj);
}
// 3)获取所有的建值
System.out.println("-------3)获取所有的建值-----------------");
Set<Entry<String, Object>> entrySet = map.entrySet();
for (Entry<String, Object> entry : entrySet) {
System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
;
}
entrySet.forEach(e -> {
System.out.println(e.getKey() + "=" + e.getValue());
});
2.HashMap与Hashtable之间的区别(重点)
同步(synchronized)既排队 线程安全的 hashtable
异步 线程非安全的 hashmap
public static void main(String[] args) {
// TreeMap
// 1)以建排序(升序和降序)
// 1.2Comparator.reverseOorder()实现降序排序
Map<String, Object> map = new TreeMap<>();
map.put("zs", 100);
map.put("ls", 90);
map.put("ww", 120);
System.out.println(map);
// 2)以值排序
// 获取键值对
Set<Entry<String, Object>> entrySet = map.entrySet();
// 将键值的方式转换成List集合
List<Map.Entry<String, Object>> lst = new ArrayList<>(entrySet);
// Collection
// 面试题:Colection与Colection的区别?
// Collection:是集合框架的顶级接口
// Collection:是集合框架的帮助类
Collections.sort(lst, new Comparator<Entry<String, Object>>() {
@Override
public int compare(Entry<String, Object> a, Entry<String, Object> b) {
return -(a.getValue().hashCode() - b.getValue().hashCode());
}
});
lst.forEach(System.out::println);
String str = "1,2,3,4,5,6,7";
String[] strings = str.split(",");
// 转换为集合
List<String> asList = Arrays.asList(str.split(","));
System.out.println(asList);
// 将数组转换为String字符串
String string = Arrays.toString(strings);
System.out.println(string);
3. 其它
3.1 Collections:工具类,提供一组静态方法操作Collection集合
3.2 Arrays:工具类,提供了一组静态方法操作数组