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

remove()を使ってMap(マップ)のnullの値(value)を持つ要素を全削除するには、whileを使います。
まず、while()を記述します。
while()の()内で、Mapからvalues()、values()からremove()を呼び出します。
そして、remove()の引数にnullを指定します。
while(numbers.values().remove(null));
上記のwhile()は、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);
while(numbers.values().remove(null));
System.out.println(numbers);
}
}
出力:
{four=4, one=1, two=2}
コメント