← Java from Scratch Lesson 67 of 88 · 10 XP

Collections

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

All lists and sets implement the common interface Collection<E>:

Collection<String> c = new ArrayList<>();      // <> — the type is inferred from the declaration on the left
c.add("sword");
c.addAll(List.of("shield", "potion"));
c.remove("shield");
c.contains("sword")    // true
c.size(), c.isEmpty()
c.retainAll(other)     // keep only what's also in other (the intersection)
c.removeAll(other)     // remove everything that's in other (the difference)
c.clear()
for (String s : c) …

Giving a variable an interface type (Collection, List, Map) rather than a class is a good habit: the implementation is then easy to swap.

Task. Two lines — the inventories of two players (words separated by spaces). Print: the common items in the order of the first inventory (retainAll), the items only the first player has (removeAll), and the sizes of the original inventories. An empty result is -.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.