Skip to content

Commit 8fa7008

Browse files
committed
update object dictionary API
1 parent 6a48dd3 commit 8fa7008

2 files changed

Lines changed: 22 additions & 4 deletions

File tree

rlib-common/src/main/java/com/ss/rlib/common/util/dictionary/ObjectDictionary.java

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,6 @@
88
import org.jetbrains.annotations.Nullable;
99

1010
import java.util.Optional;
11-
import java.util.function.BiConsumer;
12-
import java.util.function.BiFunction;
13-
import java.util.function.Function;
14-
import java.util.function.Supplier;
1511

1612
/**
1713
* The interface for implementing a key-value dictionary which using an object key.
@@ -101,6 +97,18 @@ default boolean containsKey(@NotNull K key) {
10197
throw new UnsupportedOperationException();
10298
}
10399

100+
/**
101+
* Return the value to which the specified key is mapped, or default if this dictionary
102+
* contains no mapping for the key.
103+
*
104+
* @param key the key whose associated value is to be returned.
105+
* @return the value to which the specified key is mapped, or default if this dictionary contains no mapping for the key.
106+
*/
107+
default @Nullable V getOrDefault(@NotNull K key, @NotNull V def) {
108+
var value = get(key);
109+
return value == null ? def : value;
110+
}
111+
104112
/**
105113
* Return the optional value to which the specified key is mapped, or {@code null} if this dictionary
106114
* contains no mapping for the key.

rlib-common/src/test/java/com/ss/rlib/common/test/util/dictionary/ObjectDictionaryTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,14 @@ void dictionaryOfTest() {
5353
() -> ObjectDictionary.of("Key1")
5454
);
5555
}
56+
57+
@Test
58+
void getOrDefaultTest() {
59+
60+
var dictionary = ObjectDictionary.<String, Integer>of("Key1", 1, "Key2", 2, "Key3", 3);
61+
62+
Assertions.assertEquals(1, dictionary.get("Key1"));
63+
Assertions.assertNull(dictionary.get("Key10"));
64+
Assertions.assertEquals(10, dictionary.getOrDefault("Key10", 10));
65+
}
5666
}

0 commit comments

Comments
 (0)