Ввід/вивід і потоки в 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-eachfor (type x: collection){}List, Set, Map тощоfruits: [Apple, Banana].for (String x : fruits) {
System.out.println(x);
}
Apple
Banana
Iterator<>: підтримує List, Set, Queue тощоIteratorimport java.util.Iterator;// Створіть об'єкт `Iterator` з назвою `it` для прикладного набору `fruits` Iterator<String> it = fruits.iterator(); // Метод `.hasNext()` перевіряє, чи є ще елементи while (it.hasNext()) { // Метод `.next()` повертає елемент System.out.print(it.next());}
Apple Banana
.remove() для видалення елемента з Iterator$$
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