Revise MultiValueMapCollector implementation and tests

See https://github.com/spring-projects/spring-data-commons/issues/3420
Closes gh-35958
This commit is contained in:
Sam Brannen
2025-12-10 13:35:00 +01:00
parent bfc02cda0c
commit 3731fed4ca
2 changed files with 80 additions and 19 deletions
@@ -16,9 +16,10 @@
package org.springframework.util;
import java.util.function.Function;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -26,16 +27,33 @@ import static org.assertj.core.api.Assertions.assertThat;
* Tests for {@link MultiValueMapCollector}.
*
* @author Florian Hof
* @author Sam Brannen
* @since 7.0.2
*/
class MultiValueMapCollectorTests {
@Test
void indexingBy() {
MultiValueMapCollector<String, Integer, String> collector = MultiValueMapCollector.indexingBy(String::length);
MultiValueMap<Integer, String> content = Stream.of("abc", "ABC", "123", "1234", "abcdef", "ABCDEF").collect(collector);
assertThat(content.get(3)).containsOnly("abc", "ABC", "123");
assertThat(content.get(4)).containsOnly("abcdef", "ABCDEF");
assertThat(content.get(6)).containsOnly("1234");
assertThat(content.get(1)).isNull();
void ofFactoryMethod() {
Function<Integer, String> keyFunction = i -> (i % 2 == 0 ? "even" :"odd");
Function<Integer, Integer> valueFunction = i -> -i;
var collector = MultiValueMapCollector.of(keyFunction, valueFunction);
var multiValueMap = Stream.of(1, 2, 3, 4, 5).collect(collector);
assertThat(multiValueMap).containsOnlyKeys("even", "odd");
assertThat(multiValueMap.get("odd")).containsOnly(-1, -3, -5);
assertThat(multiValueMap.get("even")).containsOnly(-2, -4);
}
@Test
void indexingByFactoryMethod() {
var collector = MultiValueMapCollector.indexingBy(String::length);
var multiValueMap = Stream.of("abc", "ABC", "123", "1234", "cat", "abcdef", "ABCDEF").collect(collector);
assertThat(multiValueMap).containsOnlyKeys(3, 4, 6);
assertThat(multiValueMap.get(3)).containsOnly("abc", "ABC", "123", "cat");
assertThat(multiValueMap.get(4)).containsOnly("1234");
assertThat(multiValueMap.get(6)).containsOnly("abcdef", "ABCDEF");
}
}