diff --git a/spring-core/src/main/java/org/springframework/util/MultiValueMap.java b/spring-core/src/main/java/org/springframework/util/MultiValueMap.java index f51fe72e06..2429f55650 100644 --- a/spring-core/src/main/java/org/springframework/util/MultiValueMap.java +++ b/spring-core/src/main/java/org/springframework/util/MultiValueMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,6 +61,19 @@ public interface MultiValueMap extends Map> { */ void addAll(MultiValueMap values); + /** + * {@link #add(Object, Object) Add} the given value, only when the map does not + * {@link #containsKey(Object) contain} the given key. + * @param key the key + * @param value the value to be added + * @since 5.2 + */ + default void addIfAbsent(K key, @Nullable V value) { + if (!containsKey(key)) { + add(key, value); + } + } + /** * Set the given single value under the given key. * @param key the key diff --git a/spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java b/spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java index 97c484835f..671baed6c9 100644 --- a/spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java +++ b/spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java @@ -47,6 +47,19 @@ public class LinkedMultiValueMapTests { assertThat(map.get("key")).isEqualTo(expected); } + @Test + public void addIfAbsentWhenAbsent() { + map.addIfAbsent("key", "value1"); + assertThat(map.get("key")).containsExactly("value1"); + } + + @Test + public void addIfAbsentWhenPresent() { + map.add("key", "value1"); + map.addIfAbsent("key", "value2"); + assertThat(map.get("key")).containsExactly("value1"); + } + @Test public void set() { map.set("key", "value1");