【JAVA8】map操作 & 删除元素的简单方法

冷不防 2021-06-25 14:26 422阅读 0赞

JAVA8-删除元素

传统的,在JAVA中得MAP中删除元素,可以这样,假设有个MAP:

  1. Map<Integer, String> map = new HashMap<>();
  2. map.put(1, "value 1");
  3. map.put(2, "value 2");
  4. map.put(3, "value 3");
  5. for(Iterator<Integer> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
  6. Integer key = iterator.next();
  7. if(key != 1) {
  8. iterator.remove();
  9. }
  10. }

而在JAVA8中,可以这样了,更为简单:

  1. // 根据map中得值去判断删除
  2. map.values().removeIf(value -> !value.contains("1"));
  3. // 根据key删除
  4. map.keySet().removeIf(key -> key != 1);
  5. //通过getkey()方法获得值去删除
  6. map.entrySet().removeIf(entry -> entry.getKey() != 1);
  7. MAP本身没办法用removeif,要通过keySetEntrySet去调用removeif方法,再看源码:
  8. /**
  9. * 移除集合中满足给定条件的所有元素,错误或者运行时异常发生在迭代时或者把条件传递给调用者的时候。
  10. *
  11. * @implSpec
  12. * 默认的实现贯穿了使用迭代器iterator的集合的所有元素。每一个匹配的元素都将被用Iterator接口中的
  13. * remove()方法移除。如果集合的迭代器不支持移除,则在第一次匹配时就会抛出异常 UnsupportedOperationException
  14. *
  15. * @param filter 令元素移除成功的条件
  16. * @return {@code true} 如果所有的元素都被移除
  17. * @throws NullPointerException 如果有一个过滤器是空的
  18. * @throws UnsupportedOperationException 如果元素不能被从该集合中移除。如果一个匹配元素不能被移除,
  19. * 通常来说,它就不支持移除操作,这时可能抛出这个异常。
  20. * @since 1.8
  21. */
  22. default boolean removeIf(Predicate<? super E> filter) {
  23. Objects.requireNonNull(filter);
  24. boolean removed = false;
  25. final Iterator<E> each = iterator();
  26. while (each.hasNext()) {
  27. if (filter.test(each.next())) {
  28. each.remove();
  29. removed = true;
  30. }
  31. }
  32. return removed;
  33. }
  34. 也可以这样用:
  35. public static void main(String[] args) {
  36. List<String> list = new ArrayList<>();
  37. list.add("a");
  38. list.add("b");
  39. list.add("c");
  40. list.add("d");
  41. // 这里单独定义了过滤
  42. Predicate<String> predicate = (s) -> s.equals("a");
  43. // 过滤掉a的元素
  44. list.removeIf(predicate);
  45. System.out.println(list.toString());
  46. }

-——————————

1.putIfAbsent

  1. // 如果这个key不存在,就put进去
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. /**
  5. * @author bincai, bincai@mobvoi.com
  6. * @date Oct 08 , 2018
  7. */
  8. public class Run {
  9. public static void main(String[] args) throws Exception {
  10. Map<Integer, String> map = new HashMap<>();
  11. map.put(1,"bincai");
  12. for (int i = 0; i < 3; i++) {
  13. map.putIfAbsent(i, "val" + i);
  14. }
  15. map.forEach((id, val) -> System.out.println(val));
  16. }
  17. }

输出:

  1. val0
  2. bincai
  3. val2

2.computeIfAbsent、computeIfPresent、compute
⑴compute
对已经存在和未存在的key都进行操作。

⑵computeIfPresent
computeIfPresent 的方法,对 指定的 在map中已经存在的key的value进行操作。
统计单词sed和magna出现的次数:

  1. public static void main(String[] args) {
  2. Map<String, Integer> wordCounts = new ConcurrentHashMap<>(10);
  3. String s =
  4. "Lorem ipsum dolor sit amet consetetur iam nonumy sadipscing " +
  5. " elitr, sed diam nonumy eirmod tempor invidunt ut erat sed " +
  6. "labore et dolore magna dolor sit amet aliquyam erat sed diam";
  7. wordCounts.put("sed", 0);
  8. wordCounts.put("magna",0);
  9. for (String t : s.split(" ")) {
  10. wordCounts.computeIfPresent(t, (k, v) -> v + 1);
  11. }
  12. System.out.println(wordCounts);
  13. }

⑶computeIfAbsent
computeIfAbsent 的方法,对 指定的 在map中未存在的key的value进行操作。
加入我们有几个学生需要根据男女分组:

  1. public static void main(String[] args) {
  2. //学生的集合
  3. List<Student> students = new ArrayList<>();
  4. students.add(new Student("张三","男",18));
  5. students.add(new Student("李四","男",20));
  6. students.add(new Student("韩梅梅","女",18));
  7. students.add(new Student("小红","女",45));
  8. //声明接收结果的 map
  9. Map<String, List<Student>> resultMap = new HashMap<>();
  10. for (Student student : students) {
  11. List<Student> s = resultMap.computeIfAbsent(student.getSex(), k -> new ArrayList<>());
  12. s.add(student);
  13. }
  14. System.out.println(resultMap);
  15. }

3.remove
根据value移除

  1. private static void testRemove(){
  2. Map<Integer, String> map = new HashMap<>();
  3. for (int i = 0; i < 3; i++) {
  4. map.putIfAbsent(i, "val" + i);
  5. }
  6. map.remove(0,"val1");
  7. map.remove(2,"val2");
  8. // 可见,key为2的被移除
  9. map.forEach((id, val) -> System.out.println(val));
  10. }

输出:

  1. val0
  2. val1

4.getOrDefault
取不到就取默认值

  1. private static void testGetOrDefault(){
  2. Map<Integer, String> map = new HashMap<>();
  3. for (int i = 0; i < 3; i++) {
  4. map.putIfAbsent(i, "val" + i);
  5. }
  6. System.out.println(map.getOrDefault(1,"bincai"));
  7. System.out.println(map.getOrDefault(10,"bincai"));
  8. }

输出:

  1. val1
  2. bincai

5.getOrDefault

  1. private static void testMerge(){
  2. Map<Integer, String> map = new HashMap<>();
  3. map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
  4. System.out.println(map.get(9)); // val9
  5. map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
  6. System.out.println(map.get(9)); // val9concat
  7. }

输出:

  1. val9
  2. val9concat

6.遍历map

  1. private static void bianlimap(){
  2. Map<String, Object> map = new HashMap<>();
  3. map.put("key1", "value1");
  4. map.put("key2", "value2");
  5. map.put("key3", "value3");
  6. map.put("key4", 4);
  7. map.put("key5", 5);
  8. map.put("key5", 'h');
  9. map.keySet().forEach(key -> System.out.println("map.get(" + key + ") = " + map.get(key)));
  10. map.entrySet().iterator().forEachRemaining(item -> System.out.println("key:value=" + item.getKey() + ":" + item.getValue()));
  11. // 推荐使用
  12. map.entrySet().forEach(entry -> System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue()));
  13. map.values().forEach(System.out::println); // 等价于map.values().forEach(value -> System.out.println(value));
  14. map.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));
  15. }

输出:

  1. map.get(key1) = value1
  2. map.get(key2) = value2
  3. map.get(key5) = h
  4. map.get(key3) = value3
  5. map.get(key4) = 4
  6. key:value=key1:value1
  7. key:value=key2:value2
  8. key:value=key5:h
  9. key:value=key3:value3
  10. key:value=key4:4
  11. key:value = key1:value1
  12. key:value = key2:value2
  13. key:value = key5:h
  14. key:value = key3:value3
  15. key:value = key4:4
  16. value1
  17. value2
  18. h
  19. value3
  20. 4
  21. key:value = key1:value1
  22. key:value = key2:value2
  23. key:value = key5:h
  24. key:value = key3:value3
  25. key:value = key4:4

发表评论

表情:
评论列表 (有 0 条评论,422人围观)

还没有评论,来说两句吧...

相关阅读