Input/Output and Streams in Java
Alex Liu
Software Development Engineer
HashSet
for the rest of the videoimport 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 loop
for (type x: collection){}
List
, Set
, Map
and morefruits
: [Apple, Banana]
.for (String x : fruits) {
System.out.println(x);
}
Apple
Banana
Iterator<>
: Supports List
, Set
, Queue
and moreIterator
classimport 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()
to remove element with 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"
Before Removal:
System.out.println(fruits);
[Apple, Banana]
After Removal:
System.out.println(fruits);
[Banana]
Ensures safe deletion and prevent ConcurrentModificationException
For-Each
loopList
(ArrayList
,LinkedList
)Set
(HashSet
,TreeSet
,LinkedHashSet
)Queue
(PriorityQueue
)Stack
(Stack
)Map
Element Removal
Iterator
List
(ArrayList
,LinkedList
)Set
(HashSet
,TreeSet
,LinkedHashSet
)Queue
(PriorityQueue
)Stack
(Stack
)Map
(Must use keySet().iterator
, values().iterator
or entrySet().iterator
)Element Removal
Input/Output and Streams in Java