package com.zyp.test;
import com.google.common.collect.Maps;
import java.util.HashMap;
public class Map18 {
public static void main(String[] args) {
HashMap<Integer, String> map = Maps.newHashMap();
String put = map.put(1, "1");
System.out.println("put->"+put);
String put1 = map.put(1, "2");
System.out.println("put1->"+put1);
String compute = map.compute(2, (K, V) -> "2");
System.out.println("compute->"+compute);
String compute1 = map.compute(2, (K, V) -> V+"b");
System.out.println("compute1->"+compute1);
String computeIfAbsent = map.computeIfAbsent(2, i -> i + "a");
System.out.println("computeIfAbsent->"+computeIfAbsent);
String computeIfAbsent2 = map.computeIfAbsent(4, i -> i + "a");
System.out.println("computeIfAbsent2->"+computeIfAbsent2);
System.out.println(map);
String computeIfPresent = map.computeIfPresent(4, (K, V) -> V + "a");
System.out.println("computeIfPresent->"+computeIfPresent);
String computeIfPresent2 = map.computeIfPresent(5, (K, V) -> V + "a");
System.out.println("computeIfPresent2->"+computeIfPresent2);
System.out.println(map);
String merge = map.merge(5, "5", (old, new1) -> old + new1);
System.out.println("merge->"+merge);
String merge2 = map.merge(5, "6", (old, new1) -> old + new1);
System.out.println("merge2->"+merge2);
String merge1 = map.merge(6, "6", (old, new1) -> old + new1);
System.out.println("merge1->"+merge1);
System.out.println(map);
}
}
使用举例:
package com.zyp.test;
import com.google.common.collect.Maps;
import java.util.HashMap;
public class MapTest {
public static void main(String[] args) {
String a="fiensdkajfhquebdjsankroiwqfhusdbvjnkwoqdas";
HashMap<Character, Integer> map = Maps.newHashMap();
for (int i = 0; i <a.length() ; i++) {
char c = a.charAt(i);
Integer value = map.get(c);
if(null==value){
value=1;
}else{
++value;
}
map.put(c, value);
}
System.out.println("map->"+map);
System.out.println();
map.clear();
for (int i = 0; i < a.length(); i++) {
map.compute(a.charAt(i),(K,V)->{
if(V==null){
V=1;
}else{
++V;
}
return V;
});
}
System.out.println("map1->"+map);
map.clear();
for (int i = 0; i < a.length(); i++) {
map.merge(a.charAt(i), 1, (s,s1)->s+s1);
}
System.out.println("map2->"+map);
}
}
|