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; }