Java の入出力とストリーム
Alex Liu
Software Development Engineer
HashSet の例import java.util.HashSet;public class SampleHashSetData { public static void main(String[] args) { HashSet<String> fruits = new HashSet<>();fruits.add("Apple"); fruits.add("Banana");} }
{Apple, Banana}
For-Each ループfor (type x: collection){}List、Set、Map などfruits: [Apple, Banana]for (String x : fruits) {
System.out.println(x);
}
Apple
Banana
Iterator<> を使用: List、Set、Queue などをサポートIterator クラスをインポートimport java.util.Iterator;// サンプル集合 `fruits` 用の `Iterator` オブジェクト it を作成 Iterator<String> it = fruits.iterator(); // `.hasNext()` は次の要素があるか確認 while (it.hasNext()) { // `.next()` で要素を取得 System.out.print(it.next());}
Apple Banana
Iterator で .remove() を使って要素を削除$$
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
String fruit = it.next();
if (fruit.startsWith("A")) {
// 先頭が `A` の要素を削除
it.remove();
}
}
// fruits は "Banana" のみ
削除前:
System.out.println(fruits);
[Apple, Banana]
削除後:
System.out.println(fruits);
[Banana]
安全に削除し、ConcurrentModificationException を防止

For-Each ループList(ArrayList、LinkedList)Set(HashSet、TreeSet、LinkedHashSet)Queue(PriorityQueue)Stack(Stack)Map要素の削除IteratorList(ArrayList、LinkedList)Set(HashSet、TreeSet、LinkedHashSet)Queue(PriorityQueue)Stack(Stack)Map(keySet().iterator、values().iterator、entrySet().iterator を使用)要素の削除Java の入出力とストリーム