Deque<String> a = new ArrayDeque<>();
// Using add()
a.add("Dog");
// Using addFirst()
a.addFirst("Cat");
// Using addLast()
a.addLast("Horse");
// [Cat, Dog, Horse]
System.out.println(a);
// Access element
System.out.println(a.peek());
// Remove element
System.out.println(a.pop());
Java Collections Framework
ArrayDeque
HashSet
Set<String> set = new HashSet<>();
if (set.isEmpty()) {
System.out.println("Empty!");
}
set.add("dog");
set.add("cat");
set.add("mouse");
set.add("snake");
set.add("bear");
if (set.contains("cat")) {
System.out.println("Contains cat");
}
set.remove("cat");
for (String element : set) {
System.out.println(element);
}
HashMap
Map<Integer, String> m = new HashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");
// Retrieving
System.out.println(m.get(6));
// Lambda forEach
m.forEach((key, value) -> {
String msg = key + ": " + value;
System.out.println(msg);
});
ArrayList
List<Integer> nums = new ArrayList<>();
// Adding
nums.add(2);
nums.add(5);
nums.add(8);
// Retrieving
System.out.println(nums.get(0));
// Indexed for loop iteration
for (int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slow
for (Integer value : nums) {
System.out.println(value);
}
Java Collections
Collection | Interface | Ordered | Sorted | Thread safe | Duplicate | Nullable |
---|---|---|---|---|---|---|
ArrayList | List | Y | N | N | Y | Y |
Vector | List | Y | N | Y | Y | Y |
LinkedList | List, Deque | Y | N | N | Y | Y |
CopyOnWriteArrayList | List | Y | N | Y | Y | Y |
HashSet | Set | N | N | N | N | One null |
LinkedHashSet | Set | Y | N | N | N | One null |
TreeSet | Set | Y | Y | N | N | N |
CopyOnWriteArraySet | Set | Y | N | Y | N | One null |
ConcurrentSkipListSet | Set | Y | Y | Y | N | N |
HashMap | Map | N | N | N | N (key) | One null (key) |
HashTable | Map | N | N | Y | N (key) | N (key) |
LinkedHashMap | Map | Y | N | N | N (key) | One null (key) |
TreeMap | Map | Y | Y | N | N (key) | N (key) |
ConcurrentHashMap | Map | N | N | Y | N (key) | N |
ConcurrentSkipListMap | Map | Y | Y | Y | N (key) | N |
ArrayDeque | Deque | Y | N | N | Y | N |
PriorityQueue | Queue | Y | N | N | Y | N |
ConcurrentLinkedQueue | Queue | Y | N | Y | Y | N |
ConcurrentLinkedDeque | Deque | Y | N | Y | Y | N |
ArrayBlockingQueue | Queue | Y | N | Y | Y | N |
LinkedBlockingDeque | Deque | Y | N | Y | Y | N |
PriorityBlockingQueue | Queue | Y | N | Y | Y | N |
Comments