基本使用
public class Demomap {
public static void main(String[] args) {
Map<String,Integer> maps = new HashMap<>();//无序
// Map<String,Integer> maps = new LinkedHashMap<>();有序
maps.put("a",1);
maps.put("b",2);
maps.put("c",3);
maps.put(null,null);
System.out.println(maps);
}
}
常用api
public class Demomap {
public static void main(String[] args) {
Map<String,Integer> maps = new HashMap<>();
Map<String,Integer> maps1 = new HashMap<>();
maps.put("a",1);
maps.put("b",2);
maps.put("c",3);
maps1.put("d",1);
maps1.put("f",2);
maps1.put("g",3);
System.out.println(maps);
// maps.clear();
maps.remove("a");// 根据key删除
System.out.println(maps.get("b")); //根据key取值
Set<String> keySets = maps.keySet();// 取出所有的key
System.out.println(keySets);
Collection<Integer> values = maps.values(); //取出所有的value
System.out.println(values);
System.out.println(maps.containsKey("b"));
System.out.println(maps.containsValue(1));
maps.putAll(maps1); //maps1所有元素添加到mpas
System.out.println(maps);
System.out.println(maps.size());
System.out.println(maps.isEmpty());
}
}
遍历
public class Demomap1 {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
map.put("c",3);
// 遍历方式一,通过key取值
Set<String> mapkey = map.keySet();
for (String key : mapkey) {
System.out.println(map.get(key));
}
// 遍历方式二
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entrie : entries){
System.out.println("key:" + entrie.getKey());
System.out.println("value:" + entrie.getValue());
}
// 遍历方式三
map.forEach(new BiConsumer<String, Integer>() {
@Override
public void accept(String key, Integer value) {
System.out.println("这是key"+key);
System.out.println("这是value"+value);
}
});
// 遍历方式三,简写
map.forEach((key,value)-> {
System.out.println("这是key"+key);
System.out.println("value"+value);
});
}
}
排序
//只能针对key进行排序
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
public class Treesort {
public static void main(String[] args) {
//自定义排序
Map<Student,Integer> maps = new TreeMap<>((o1,o2)->o2.getHeight() - o1.getHeight());
maps.put(new Student(1),1);
maps.put(new Student(2),1);
maps.put(new Student(3),1);
System.out.println(maps);
}
}
class Student{
private int height;
public Student(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return height == student.height;
}
@Override
public int hashCode() {
return Objects.hash(height);
}
@Override
public String toString() {
return "Student{" +
"height=" + height +
'}';
}
}