Java Collections Framework and generics, step by step

You will build it by hand

TAD ListaTAD PilaTAD Cola

In the next lessons, to see how they work inside

Java already ships it

ArrayListHashMapArrayDeque

Thirty years of tuning and millions of applications

Using a tool is not the same as understanding it

Good: the type is the interface

List<String> nombres = new ArrayList<>(); Map<String, Integer> stock = new HashMap<>();

Bad: you tie yourself to the implementation

ArrayList<String> nombres = new ArrayList<>();

Switching to LinkedList means touching one word

List<String> nombres = new LinkedList<>();

entrySet()

for (Map.Entry<String, Integer> e : stock.entrySet())

Each entry carries getKey() and getValue()

merge

contador.merge(palabra, 1, Integer::sum);

Counts frequencies with no if at all

getOrDefault

stock.getOrDefault("azúcar", 0)

A default value instead of null

putIfAbsent

mapa.putIfAbsent(clave, valor);

Stores only if the key is missing

computeIfAbsent

mapa.computeIfAbsent(k, x -> new ArrayList<>()).add(v);

Builds a map of lists

ArrayDeque

Stack and queue

Inserts and removes at the ends in O(1)

PriorityQueue

The highest priority comes out

Not the one that arrived first

You will implement them by hand in ADT Stack and ADT Queue

Generic class

public class Caja<T>

The type parameter goes between <> after the name

Generic method

public static <T> T primero(List<T> lista)

Its own type parameter, before the return type

Bounded type

<T extends Comparable<T>>

So you can safely call compareTo

By convention, one capital letter

T · type E · element K · key V · value R · result

Generics exist only at compile time

List<String> == List<Integer> → List
Insertion order and access by index ArrayList
Lots of inserts and removals at the ends ArrayDeque
Unique elements, order does not matter HashSet
Unique elements, always sorted TreeSet
Key → value, very fast access HashMap
Key → value, walked in key order TreeMap
Key → value, in insertion order LinkedHashMap
Always take the highest priority PriorityQueue
ArrayList<T> x = new ArrayList<>()No equals/hashCode in HashSet/HashMapModifying while walking with for-eachmapa.get(k) without handling nullLinkedList "because inserting is faster"Mutable key in a HashMapModifying a List.of(...) list

1 Step

Normalize the text

Lowercase, no punctuation

2 Step

Count with a Map

Map<String, Integer>

3 Step

Sort by frequency

Descending, then alphabetical

4 Step

Distinct words

The keys, as a Set

5 Step

Skip the stop words

de, la, el, y, que…

contains on VACIAS

Set · O(1) List · O(n)
1 · Declare with the interface2 · Map does not extend Collection3 · Generics: the error comes earlier4 · Type erasure5 · hashCode picks the bucket6 · equals picks the element7 · merge · computeIfAbsent · getOrDefault8 · Choosing well is performance

CursoDeJava · l15_java_collections_framework_y_genericos

Runnable programs for every section