Skip to content

Commit b21b27c

Browse files
committed
Add MultiValueMap.addIfAbsent method
Closes gh-23111
1 parent 0757eae commit b21b27c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

spring-core/src/main/java/org/springframework/util/MultiValueMap.java

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -61,6 +61,19 @@ public interface MultiValueMap<K, V> extends Map<K, List<V>> {
6161
*/
6262
void addAll(MultiValueMap<K, V> values);
6363

64+
/**
65+
* {@link #add(Object, Object) Add} the given value, only when the map does not
66+
* {@link #containsKey(Object) contain} the given key.
67+
* @param key the key
68+
* @param value the value to be added
69+
* @since 5.2
70+
*/
71+
default void addIfAbsent(K key, @Nullable V value) {
72+
if (!containsKey(key)) {
73+
add(key, value);
74+
}
75+
}
76+
6477
/**
6578
* Set the given single value under the given key.
6679
* @param key the key

spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,19 @@ public void add() {
4747
assertThat(map.get("key")).isEqualTo(expected);
4848
}
4949

50+
@Test
51+
public void addIfAbsentWhenAbsent() {
52+
map.addIfAbsent("key", "value1");
53+
assertThat(map.get("key")).containsExactly("value1");
54+
}
55+
56+
@Test
57+
public void addIfAbsentWhenPresent() {
58+
map.add("key", "value1");
59+
map.addIfAbsent("key", "value2");
60+
assertThat(map.get("key")).containsExactly("value1");
61+
}
62+
5063
@Test
5164
public void set() {
5265
map.set("key", "value1");

0 commit comments

Comments
 (0)