LoginSignup
8
6

More than 5 years have passed since last update.

Collectors.toMap の NullPointerException に気をつける

Last updated at Posted at 2015-08-04

以下のテストは成功しません。

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;

public class MapCollectorTest {

    @Test
    public void test() {
        Map<Integer, Object> map1 = new HashMap<>();
        map1.put(1, null);

        Map<Integer, Object> map2 =
                map1.entrySet().stream().collect(
                        Collectors.toMap(x -> 1 + x.getKey(), Map.Entry::getValue));

        assertThat(map2, notNullValue());
    }

}

動かしてみるとわかるのですが、NullPointerException が発生します。理由は Collectors.toMap の中で Map.merge が使われていて、Map.merge では value が null の時にも NullPointerException が発生するからです。

stackoverflow (Java 8 NullPointerException in Collectors.toMap) でも解説されています。

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6