HashMap(由键决定特点):无序、不重复、无索引
LinkedHashMap(由键决定特点):有序,不重复,无索引
TreeMap(由键决定特点):按照大小默认排序升序、不重复、无索引
常用方法
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author Pickle
* @version V1.0
* @date 2024/3/9 16:50
*/
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map.put("d", 4);
map.put("a", 5);
System.out.println(map);
map.clear();
System.out.println(map.isEmpty());
map.put("a",1);
map.put("b",2);
map.put("c",3);
map.put("d",4);
System.out.println(map.get("a"));
System.out.println(map.remove("a"));
System.out.println(map);
System.out.println(map.containsKey("b"));
System.out.println(map.containsValue(3));
//因为Map的键是无重复,所以放入set中是合理的
final Set<String> strings = map.keySet();
System.out.println(strings);
//因为map的值是可以重复的,所以放到Collection中是合理的
final Collection<Integer> values = map.values();
System.out.println(values);
}
}
Map的遍历
键找值
import java.util.*;
/**
* @author Pickle
* @version V1.0
* @date 2024/3/9 16:50
*/
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("a", 0);
map.put("b", 1);
map.put("c", 2);
map.put("d", 3);
map.put("e", 4);
map.put("f", 5);
map.put("g", 6);
map.put("h", 7);
final Set<String> keys = map.keySet();
System.out.println(keys); //[a, b, c, d, e, f, g, h]
for (String key : keys){
System.out.print(map.get(key)); //01234567
}
}
}
键值对
import java.util.*;
/**
* @author Pickle
* @version V1.0
* @date 2024/3/9 16:50
*/
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("a", 0);
map.put("b", 1);
map.put("c", 2);
map.put("d", 3);
map.put("e", 4);
map.put("f", 5);
map.put("g", 6);
map.put("h", 7);
for (Map.Entry<String, Integer> kv : map.entrySet()){
System.out.print(kv.getKey()+ kv.getValue() + " "); //a0 b1 c2 d3 e4 f5 g6 h7
}
}
}
Lambda
import java.util.*;
import java.util.function.BiConsumer;
/**
* @author Pickle
* @version V1.0
* @date 2024/3/9 16:50
*/
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("a", 0);
map.put("b", 1);
map.put("c", 2);
map.put("d", 3);
map.put("e", 4);
map.put("f", 5);
map.put("g", 6);
map.put("h", 7);
// map.forEach(new BiConsumer<String, Integer>() {
// @Override
// public void accept(String s, Integer integer) {
// System.out.print(s + " " + integer + " "); //a 0 b 1 c 2 d 3 e 4 f 5 g 6 h 7
// }
// });
map.forEach((k,v)->{
System.out.print(k + " " + v + " ");
});
}
}
HashMap
底层同HashSet,为哈希表(数组+链表+红黑树(Java8))
LinkedHashMap
底层同LinkedHashSet
TreeMap
标签:Map,map,System,put,集合,println,out From: https://www.cnblogs.com/poteitoutou/p/18062997底层同TreeMap