Mapéå
Map éå
Java8 é对 map æä½å¢å äºä¸äºæ¹æ³ï¼é常æ¹ä¾¿
1ãå é¤å
ç´ ä½¿ç¨removeIf()æ¹æ³ã
/**
* @description:
* @author: ç¨åºå大彬
* @time: 2021-09-07 00:03
*/
public class MapTest {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "dabin1");
map.put(2, "dabin2");
//å é¤value没æå«æ1çé®å¼å¯¹
map.values().removeIf(value -> !value.contains("1"));
System.out.println(map);
}
/**
* output
* {1=dabin1}
*/
}
2ãputIfAbsent(key, value) 妿æå®ç key ä¸åå¨ï¼å put è¿å»ã
/**
* @description:
* @author: ç¨åºå大彬
* @time: 2021-09-07 00:08
*/
public class MapTest1 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "大彬1");
for (int i = 0; i < 3; i++) {
map.putIfAbsent(i, "大彬" + i);
}
map.forEach((id, val) -> System.out.print(val + ", "));
}
/**
* output
* 大彬0, 大彬1, 大彬2
*/
}
3ãmap 转æ¢ã
/**
* @author: ç¨åºå大彬
* @time: 2021-09-07 08:15
*/
public class MapTest2 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("1", 1);
map.put("2", 2);
Map<String, String> newMap = map.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(), e -> "大彬" + String.valueOf(e.getValue())));
newMap.forEach((key, val) -> System.out.print(val + ", "));
}
/**
* output
* 大彬1, 大彬2,
*/
}
4ãmapéåã
/**
* @author: ç¨åºå大彬
* @time: 2021-09-07 08:31
*/
public class MapTest3 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "大彬1");
map.put(2, "大彬2");
//æ¹å¼1
map.keySet().forEach(k -> {
System.out.print(map.get(k) + ", ");
});
//æ¹å¼2
map.entrySet().iterator().forEachRemaining(e -> System.out.print(e.getValue() + ", "));
//æ¹å¼3
map.entrySet().forEach(entry -> {
System.out.print(entry.getValue() + ", ");
});
//æ¹å¼4
map.values().forEach(v -> {
System.out.print(v + ", ");
});
}
}
Loading...