• java8新特性Map的创建与merge


    Map集合的创建与merge操作:

         Student student1 = new Student("Johnson",UUID.randomUUID()); Student student2 = new Student("Lily",UUID.randomUUID()); Student student3 = new Student("KangKang",UUID.randomUUID()); //创建 Map<UUID, Student> collect1 = Stream.of(new AbstractMap.SimpleEntry<>(student1.getSid(), student1)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map<UUID, List<Student>> collect2 = Stream.of(new AbstractMap.SimpleEntry<>(student1.getSid(), Lists.newArrayList(student1))).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map<UUID, Map<UUID, Student>> collect3 = Maps.newHashMap(); //合并(添加) collect1.merge(student2.getSid(), student2, (oldValue, value) -> value.getSid().compareTo(oldValue.getSid())==0 ? value : oldValue); collect2.merge(student2.getSid(), newArrayList(student2), (oldValue, value) -> Stream.concat(oldValue.stream(), value.stream()).collect(toList())); collect3.merge(student3.getSid(),collect1,(oldValue,value)->{ oldValue.putAll(value); return oldValue; }); static class Student{ private String name; private UUID sid; public Student(String name, UUID sid) { this.name = name; this.sid = sid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public UUID getSid() { return sid; } public void setSid(UUID sid) { this.sid = sid; } }

    merge() 可以这么理解:它将新的值赋值到 key (如果不存在)或更新给定的key 值对应的 value,其源码如下:
       default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
            Objects.requireNonNull(remappingFunction);
            Objects.requireNonNull(value);
            V oldValue = get(key);
            V newValue = (oldValue == null) ? value :
                       remappingFunction.apply(oldValue, value);
            if(newValue == null) {
                remove(key);
            } else {
                put(key, newValue);
            }
            return newValue;
        }
    
    
    
     
  • 相关阅读:
    ArcEngine:GP使用!没道理的错误!
    XMLHttpRequest的亲密接触(1)——简单讲解
    XMLHttpRequest的亲密接触(2.2)——表单提交
    初入Ajax,需要明确的Web工作原理
    文章收藏明细
    【备忘】Oracle10g 创建、删除表空间、创建、授权用户
    proxool的使用总结
    Java操作压缩与解压缩
    解决jquery ui dialog中调用datepicker时日期选择控件被遮挡的问题
    如何读取jar包中的xml等资源文件
  • 原文地址:https://www.cnblogs.com/JohnsonLiu/p/14392836.html
Copyright © 2020-2023  润新知