どうも、ちょげ(@chogetarou)です。
removeAll()を使ってMap(マップ)のnullの値(value)を持つ要素を全削除する方法を紹介します。
方法

removeAll()を使ってMap(マップ)のnullの値(value)を持つ要素を全削除するには、Collections.singleton()を使います。
まず、Mapからvalues()、values()からremoveAll()を呼び出します。
removeAll()の引数にCollections.singleton()を指定します。
そして、Collections.singleton()の引数にnullを指定します。
map.values().removeAll(Collections.singleton(null));
上記のremoveAll()は、values()を呼び出したMapのnullの値を持つ要素を全削除します。
使用例
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Map<String, Integer> numbers = new HashMap<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", null);
numbers.put("four", 4);
numbers.put("five", null);
numbers.values().removeAll(Collections.singleton(null));
System.out.println(numbers);
}
}
出力:
{four=4, one=1, two=2}
コメント