java Map
https://www.cnblogs.com/lzq198754/p/5780165.html
Map.一组成对的"键值对"对象,允许你使用键来查找值,ArrayList允许你使用数字来查找值,因此在某种意义上讲,它将数字与对象关联在了一起.映射表允许我们使用另一个对象,它也被称为"关联数组",因为它将某些对象与另外一些对象关联在了一起,或者被称为"字典",因为你可以使用键对象来查找值对象,就像在字典中使用单词来定义一样,Map是强大的编程工具
将对象映射到其它对象的能力是一种解决编程问题的杀手锏,例如考虑一个程序,它将接受来自Java的Random类到随机性,在理想状态下,Random可以产生理想的数字分布,但要向测试它,则需要产生大量的随机数,不对落入各种不同范围的数字进行计数,Map很容易可以解决该问题,
通用Map有:HashMap、Hashtable、Properties、LinkedHashMap、IdentityHashMap、TreeMap、WeakHashMap、ConcurrentHashMap
抽象Map:AbstractMap
java Map类
package java.util; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Function; import java.io.Serializable; public interface Map<K,V> { int size(); boolean isEmpty();//判空 boolean containsKey(Object key); //检查容器中是否包含键key boolean containsValue(Object value);//检查容器中是否包含值value V get(Object key); //查询键是否在容器中,如果键不在容器中,返回null,否则返回键对应的value V put(K key, V value); //设置键key,和键的值value,key(键)在容器中不能重复 V remove(Object key); //移除键key及其value void putAll(Map<? extends K, ? extends V> m); void clear(); //清空Map Set<K> keySet(); //返回键的Set Collection<V> values(); //返回值的Collection Set<Map.Entry<K, V>> entrySet(); //返回 Map 中所包含映射的 Set 视图。Set 中的每个元素都是一个 Map.Entry 对象 //可以使用Iterator调用Map.Entry 对象,Map.Entry对象又可以使用Entry的方法获取键和值 interface Entry<K,V> { //Entry的用法 for(Map.Entry<Integer,String> entry: map.entrySet())
// {entry.getValue();entry.getKey( )}
K getKey(); V getValue(); V setValue(V value); boolean equals(Object o); int hashCode(); public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() { return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getKey().compareTo(c2.getKey()); } public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() { return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getValue().compareTo(c2.getValue()); } public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) { Objects.requireNonNull(cmp); return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey()); } public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) { Objects.requireNonNull(cmp); return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue()); } } boolean equals(Object o); int hashCode(); default V getOrDefault(Object key, V defaultValue) { V v; return (((v = get(key)) != null) || containsKey(key)) ? v : defaultValue; } default void forEach(BiConsumer<? super K, ? super V> action) {
//用法 map.forEach((k,v)-> System.out.println(k+ " " + v));;
Objects.requireNonNull(action); for (Map.Entry<K, V> entry : entrySet()) { K k; V v; try { k = entry.getKey(); v = entry.getValue(); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } action.accept(k, v); } } default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Objects.requireNonNull(function); for (Map.Entry<K, V> entry : entrySet()) { K k; V v; try { k = entry.getKey(); v = entry.getValue(); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } // ise thrown from function is not a cme. v = function.apply(k, v); try { entry.setValue(v); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } } } default V putIfAbsent(K key, V value) { V v = get(key); if (v == null) { v = put(key, value); } return v; } default boolean remove(Object key, Object value) { Object curValue = get(key); if (!Objects.equals(curValue, value) || (curValue == null && !containsKey(key))) { return false; } remove(key); return true; } default boolean replace(K key, V oldValue, V newValue) { Object curValue = get(key); if (!Objects.equals(curValue, oldValue) || (curValue == null && !containsKey(key))) { return false; } put(key, newValue); return true; } default V replace(K key, V value) { V curValue; if (((curValue = get(key)) != null) || containsKey(key)) { curValue = put(key, value); } return curValue; } default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { Objects.requireNonNull(mappingFunction); V v; if ((v = get(key)) == null) { V newValue; if ((newValue = mappingFunction.apply(key)) != null) { put(key, newValue); return newValue; } } return v; } default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); V oldValue; if ((oldValue = get(key)) != null) { V newValue = remappingFunction.apply(key, oldValue); if (newValue != null) { put(key, newValue); return newValue; } else { remove(key); return null; } } else { return null; } } default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); V oldValue = get(key); V newValue = remappingFunction.apply(key, oldValue); if (newValue == null) { // delete mapping if (oldValue != null || containsKey(key)) { // something to remove remove(key); return null; } else { // nothing to do. Leave things as they were. return null; } } else { // add or replace old mapping put(key, newValue); return newValue; } } default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); Objects.requireNonNull(value); V oldValue = get(key); V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value); if(newValue == null) { remove(key); } else { put(key, newValue); } return newValue; } }
//: holding/Statistics.java // Simple demonstration of HashMap. package object; import java.util.*; public class Statistics { public static void main(String[] args) { Random rand = new Random(47); Map<Integer,Integer> m = new HashMap<Integer,Integer>(); for(int i = 0; i < 10000; i++) { // Produce a number between 0 and 20: int r = rand.nextInt(20); Integer freq = m.get(r);//get()返回键的值,put()设置键和值 m.put(r, freq == null ? 1 : freq + 1);//键是Random产生的值,值是该数字的字数 } System.out.println(m); } } /* Output: {15=497, 4=481, 19=464, 8=468, 11=531, 16=533, 18=478, 3=508, 7=471, 12=521, 17=509, 2=489, 13=506, 9=549, 6=519, 1=502, 14=477, 10=513, 5=503, 0=481} *///:~
下列示例演示了String
//: holding/PetMap.java package object; import typeinfo.pets.*; import java.util.*; import static net.mindview.util.Print.*; public class PetMap { public static void main(String[] args) { Map<String,Pet> petMap = new HashMap<String,Pet>(); petMap.put("My Cat", new Cat("Molly")); petMap.put("My Dog", new Dog("Ginger")); petMap.put("My Hamster", new Hamster("Bosco")); print(petMap); Pet dog = petMap.get("My Dog"); print(dog); print(petMap.containsKey("My Dog"));//检查容器中是否包含键"My Dog" print(petMap.containsValue(dog)); //检查容器中是否包含value"dog"
} } /* Output: {My Cat=Cat Molly, My Hamster=Hamster Bosco, My Dog=Dog Ginger} Dog Ginger true true *///:~
map可以很容易扩展到多维,而我们只需要将其值设置为map(这些Map的值可以是其它容器,甚至是map),因此我们能很容易将容器组合起来从而快速生成强大的数据结构,下面是一个示例
//: holding/MapOfList.java package object; import typeinfo.pets.*; import java.util.*; import static net.mindview.util.Print.*; public class MapOfList { public static Map<Person, List<? extends Pet>> petPeople = new HashMap<Person, List<? extends Pet>>(); static { petPeople.put(new Person("Dawn"), Arrays.asList(new Cymric("Molly"),new Mutt("Spot"))); petPeople.put(new Person("Kate"), Arrays.asList(new Cat("Shackleton"), new Cat("Elsie May"), new Dog("Margrett"))); petPeople.put(new Person("Marilyn"), Arrays.asList( new Pug("Louie aka Louis Snorkelstein Dupree"), new Cat("Stanford aka Stinky el Negro"), new Cat("Pinkola"))); petPeople.put(new Person("Luke"), Arrays.asList(new Rat("Fuzzy"), new Rat("Fizzy"))); petPeople.put(new Person("Isaac"), Arrays.asList(new Rat("Freckly"))); } public static void main(String[] args) { print("People: " + petPeople.keySet()); //返回键的Set print("Pets: " + petPeople.values()); //返回值的Collection for(Person person : petPeople.keySet()) { print(person + " has:"); for(Pet pet : petPeople.get(person)) print(" " + pet); } } } /* Output: People: [Person Luke, Person Marilyn, Person Isaac, Person Dawn, Person Kate] Pets: [[Rat Fuzzy, Rat Fizzy], [Pug Louie aka Louis Snorkelstein Dupree, Cat Stanford aka Stinky el Negro, Cat Pinkola], [Rat Freckly], [Cymric Molly, Mutt Spot], [Cat Shackleton, Cat Elsie May, Dog Margrett]] Person Luke has: Rat Fuzzy Rat Fizzy Person Marilyn has: Pug Louie aka Louis Snorkelstein Dupree Cat Stanford aka Stinky el Negro Cat Pinkola Person Isaac has: Rat Freckly Person Dawn has: Cymric Molly Mutt Spot Person Kate has: Cat Shackleton Cat Elsie May Dog Margrett *///:~