java8工具类使用

1:map的使用

computeIfPresent  ,如果键已经存在,将键和值作为参数传到函数式中,计算返回新的值
import java.util.HashMap;
import java.util.Map;

/**
 * @program: GradleTestUseSubModule
 * @author: Yafei Li
 * @create: 2018-06-27 09:18
 **/
public class Test2 {
    public static void main(String[] args){
        Map<Integer,String> map = new HashMap<>();

        map.putIfAbsent(3, "hi");

        map.computeIfPresent(3, (num, val) -> {  //num是键, val是键对应的值
            System.out.println(num); //3
            System.out.println(val);  //hi
            return val + num;
        });
        String s = map.get(3);
        System.out.println(s);  //hi3


    }
}

2:computeIfAbsent  如果不存在改键,将键作为参数传入到函数式,返回一个该键对应的值。

        map.computeIfAbsent(2, (key)->{
            System.out.println(key);  //2
            return key+"hello";
        });

3:computeIfPresent 计算过后,返回值为该键对应的值,可以在后面直接对该值操作

            String set1 = map.computeIfPresent(key, (val, set) -> {
              
                return set+"hello";
            });

4:merge

import java.util.HashMap;
import java.util.Map;

/**
 * @program: GradleTestUseSubModule
 * @author: Yafei Li
 * @create: 2018-06-27 09:34
 **/
public class Test3 {
    public static void main(String[] args){
        Map<Integer,String> map = new HashMap<>();
        map.merge(9, "val9", (value, newValue) -> {
            System.out.println(value);    //不输出,因为键值不存在,不进行计算
            System.out.println(newValue);
            value.concat(newValue);
            return value;
        });
        String s = map.get(9);// val9
        System.out.println(s);
        map.merge(9, "val9", (value, newValue) -> {
            System.out.println("value:  "+value);
            System.out.println("newValue:  "+newValue);
            value.concat(newValue);
            return value;
        });
        map.get(9);
        System.out.println(s);

        /**结果
         val9
         value:  val9
         newValue:  val9
         val9
         */

    }
}

Merge做的事情是如果键名不存在则插入,否则则对原键对应的值做合并操作并重新插入到map中。

猜你喜欢

转载自www.cnblogs.com/liyafei/p/9232437.html