牛骨文教育服务平台(让学习变的简单)
博文笔记

hashmap的几个重要函数

创建时间:2016-07-18 投稿人: 浏览次数:546
  1. V compute(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
  2. V computeIfAbsent(K key,Function<? super K,? extends V> mappingFunction)
  3. V computeIfPresent(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
  4. V merge(K key,V value,BiFunction<? super V,? super V,? extends V> remappingFunction)
  5. void forEach(BiConsumer<? super K,? super V> action)
写了个小例子,展示这几个函数的用法:
package halve;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.function.BiConsumer;

/**
 * Created by fhqplzj on 16-7-18 at 上午9:24.
 */
public class Lotus {
    public static void main(String[] args) {
        String[] data = "a b c d a b c a b a".split(" ");
        /**
         * V computeIfAbsent(K key,Function<? super K,? extends V> mappingFunction)
         */
        HashMap<String, LinkedList<String>> map1 = new HashMap<>();
        for (String s : data) {
            map1.computeIfAbsent(s, s1 -> new LinkedList<>()).add(s);
        }
        System.out.println("map1 = " + map1);
        System.out.println();
        /**
         * V computeIfPresent(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
         */
        for (String s : data) {
            map1.computeIfPresent(s, (s1, strings) -> {
                System.out.println("key=" + s1 + ",value=" + strings);
                return strings;
            });
        }
        System.out.println("map1 = " + map1);
        System.out.println();
        /**
         * V compute(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
         */
        for (String s : data) {
            map1.compute(s, (s1, strings) -> {
                System.out.println("key=" + s1 + ",size=" + strings.size() + ",value=" + strings);
                return strings;
            }).add("x");
        }
        System.out.println("map1 = " + map1);
        System.out.println();
        /**
         * V merge(K key,V value,BiFunction<? super V,? super V,? extends V> remappingFunction)
         */
        HashMap<String, String> map2 = new HashMap<>();
        for (String s : data) {
            map2.merge(s, s, String::concat);
        }
        System.out.println("map2 = " + map2);
        System.out.println();
        HashMap<String, Integer> map3 = new HashMap<>();
        for (String s : data) {
            map3.merge(s, 1, (x, y) -> x + y);
        }
        System.out.println("map3 = " + map3);
        System.out.println();
        /**
         * void forEach(BiConsumer<? super K,? super V> action)
         */
        BiConsumer<String, Integer> biConsumer = (s, integer) -> System.out.println(s + " occurs " + integer + " times!");
        map3.forEach(biConsumer);
    }
}


声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。