Input/Output and Streams in Java
Alex Liu
Software Development Engineer
HashSet pro zbytek videaimport 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 loopfor (type x: collection){}List, Set, Map a dalšífruits: [Apple, Banana].for (String x : fruits) {
System.out.println(x);
}
Apple
Banana
Iterator<>: podporuje List, Set, Queue a dalšíIteratorimport java.util.Iterator;// Create `Iterator` object named `it` for sample set `fruits` Iterator<String> it = fruits.iterator(); // Use `.hasNext()` method checks if more elements exist while (it.hasNext()) { // User `.next()` retrieves the element System.out.print(it.next());}
Apple Banana
.remove() k odebrání prvku pomocí Iterator$$
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
String fruit = it.next();
if (fruit.startsWith("A")) {
// Remove element if element startsWith `A`
it.remove();
}
}
// fruits now contains only "Banana"
Před odebráním:
System.out.println(fruits);
[Apple, Banana]
Po odebrání:
System.out.println(fruits);
[Banana]
Zajišťuje bezpečné mazání a zabraňuje výjimce ConcurrentModificationException

For-Each smyčkaList(ArrayList,LinkedList)Set(HashSet,TreeSet,LinkedHashSet)Queue(PriorityQueue)Stack(Stack)MapElement RemovalIteratorList(ArrayList,LinkedList)Set(HashSet,TreeSet,LinkedHashSet)Queue(PriorityQueue)Stack(Stack)Map (nutno použít keySet().iterator, values().iterator nebo entrySet().iterator)Element RemovalInput/Output and Streams in Java