diff --git a/spring-core/src/main/java/org/springframework/util/CollectionUtils.java b/spring-core/src/main/java/org/springframework/util/CollectionUtils.java index 1cd16243fd31..c1c0a60a080d 100644 --- a/spring-core/src/main/java/org/springframework/util/CollectionUtils.java +++ b/spring-core/src/main/java/org/springframework/util/CollectionUtils.java @@ -482,9 +482,8 @@ public MultiValueMapAdapter(Map> map) { @Override @Nullable - public V getFirst(K key) { - List values = this.map.get(key); - return (values != null ? values.get(0) : null); + public V getFirst(@Nullable K key) { + return firstElement(this.map.get(key)); } @Override @@ -521,7 +520,7 @@ public void setAll(Map values) { @Override public Map toSingleValueMap() { LinkedHashMap singleValueMap = new LinkedHashMap<>(this.map.size()); - this.map.forEach((key, value) -> singleValueMap.put(key, value.get(0))); + this.map.forEach((key, value) -> singleValueMap.put(key, firstElement(value))); return singleValueMap; } @@ -603,5 +602,4 @@ public String toString() { return this.map.toString(); } } - } diff --git a/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java b/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java index fa781881b0b5..75822120fe8f 100644 --- a/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -28,6 +28,7 @@ import java.util.Properties; import java.util.Set; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -210,6 +211,20 @@ void hasUniqueObject() { assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); } + @Test + void noArrayIndexOutOfBoundsException() { + HashMap> mostlyEmptyMap = new HashMap<>(); + mostlyEmptyMap.put("test", new ArrayList<>()); + + MultiValueMap multiValueMap = CollectionUtils.toMultiValueMap(mostlyEmptyMap); + Assertions.assertAll( + () -> assertThat(multiValueMap.getFirst(null)).isNull(), + () -> assertThat(multiValueMap.getFirst("test")).isNull(), + () -> assertThat(multiValueMap.toSingleValueMap().get(null)).isNull(), + () -> assertThat(multiValueMap.toSingleValueMap().get("test")).isNull() + ); + } + private static final class Instance {