Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • Practice with Collections : 22

    • Maps and Sets : 21

    • Lists and Type Parameters : 20

    • Imports and Libraries : 19

    • Multidimensional Arrays : 18

    • Practice with Strings : 17

    • null : 16

    • Algorithms and Strings : 15

    • Strings : 14

    • Functions and Algorithms : 13

    • Practice with Functions : 12

    • More About Functions : 11

    • Errors and Debugging : 10

    • Functions : 9

    • Practice with Loops and Algorithms : 8

    • Algorithms I : 7

    • Loops : 6

    • Arrays : 5

    • Compound Conditionals : 4

    • Conditional Expressions and Statements : 3

    • Operations on Variables : 2

    • Variables and Types : 1

    • Hello, world! : 0

    Maps and Sets

    import java.util.Map;
    import java.util.HashMap;
    Map<String, Integer> scores = new HashMap<>();
    scores.put("you@illinois.edu", 100);
    scores.put("me@illinois.edu", 100);
    System.out.println(scores);

    This lesson introduces two new extremely useful data structures: maps and sets. Together, maps and lists can be used to solve almost any problem. And sets have their uses as well. So let’s get started!

    Maps
    Maps

    Maps represent a fundamentally new data structure for us to consider. So far we’ve looked at data structures that put items in order—like arrays and lists. We’ve also discussed using higher-dimensional arrays when needed to represent higher-dimensional data.

    Maps are quite different. They don’t put items in order. Rather, they allow us to store and look up mappings between one thing and other.

    More specifically, maps store mappings between keys and values. Each key in a map maps to just one value. However, the same value can be mapped to by multiple keys.

    Map Operations
    Map Operations

    Let’s make this more concrete by looking at a few examples. In Java, to create a map we’ll import java.util.Map and java.util.HashMap, similarly to how we imported java.util.List and java.util.ArrayList when working with lists:

    import java.util.Map;
    import java.util.HashMap;
    Map<String, String> map = new HashMap<>();

    Note that, like Lists, Java Maps also utilize type parameters within the angle brackets: <String, String> in the example above. However, Maps require two type parameters: one for the key, and a second for the value. Also note that we use the diamond operator <> on the right, since the type parameters for the HashMap are the same as for the Map. Don’t worry too much about the hash in HashMap yet, although we’ll return to this later!

    The map we created above can be used to map Strings to other Strings:

    import java.util.Map;
    import java.util.HashMap;
    Map<String, String> map = new HashMap<>();
    map.put("challen", "Geoffrey Challen"); // add mapping from challen -> Geoffrey Challen
    map.put("colleenl", "Colleen Lewis"); // add mapping from colleenl -> Colleen Lewis
    System.out.println(map);
    map.put("challen", "Geoff Challen"); // replace mapping for challen with Geoff Challen
    System.out.println(map);

    We can add mappings to our Map using put, which accepts a key as the first parameter and a value as the second parameter. We also show how a second call to put replaces the mapping for “challen”, since each key in the map maps to a single value.

    Note that a map can have multiple keys that map to the same value:

    import java.util.Map;
    import java.util.HashMap;
    Map<String, String> map = new HashMap<>();
    map.put("student1", "A Student");
    map.put("student2", "A Student");
    System.out.println(map);

    To retrieve values from a Map we use the get method, which accepts a single parameter: the key to look up in the Map.

    import java.util.Map;
    import java.util.HashMap;
    Map<String, String> map = new HashMap<>();
    map.put("challen", "Geoff Challen");
    map.put("colleenl", "Colleen Lewis");
    System.out.println(map.get("challen")); // retrieve mapping for "challen"
    System.out.println(map.get("student1")); // retrieve mapping for "student1"

    get returns the value mapped to by that key, or null if that key does not exist in the Map. Sometimes we also refer to this as looking up the key in the map: so looking up the mapping for “challen” or “student1” in the example above.

    Map Example
    Map Example

    Maps are great for solving problems where we need to save and look up information based on a key. Let’s look at an example that may hit close to home: Recording scores on a homework problem!

    import java.util.Map;
    import java.util.HashMap;
    String scores = """
    you@illinois.edu,0
    you@illinois.edu,9
    me@illinois.edu,0
    you@illinois.edu,10
    you@illinois.edu,1
    me@illinois.edu,1
    me@illinois.edu,0
    you@illinois.edu,0""";
    Map<String, Integer> computeScores(String input) {
    Map<String, Integer> map = new HashMap<>();
    // Parse the CSV containing scores
    for (String line : input.split("\n")) {
    String[] parts = line.split(",");
    String email = parts[0];
    int score = Integer.parseInt(parts[1]);
    System.out.println(email + "->" + score);
    }
    return null;

    Map Iteration
    Map Iteration

    If you want to iterate over all of the mappings in a Java Map, there are a few different ways to do that:

    import java.util.Map;
    import java.util.HashMap;
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "one");
    map.put(2, "two");
    map.put(4, "four");
    for (Map.Entry<Integer, String> entry : map.entrySet()) {
    // each entry has a .getKey() and a .getValue() method
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
    }
    // map.keySet() will return a list of all the map keys
    for (int key : map.keySet()) {
    System.out.println(key);
    System.out.println(map.get(key));
    }

    Practice: Word Count With Map

    Created By: Geoffrey Challen
    / Version: 2021.9.0

    Given a non-null String containing words separated by the "_" character, write a method wordCount that return a Map<String, Integer> containing the number of times that each part appears in the String.

    So, for example, given the String "Xyz_Chuchu_Chuchu_Xyz_Ferdie", you would return a map with three mappings: "Xyz" to 2, "Chuchu" to 2, and "Ferdie" to 1.

    Sets
    Sets

    Before we wrap up, let’s briefly examine one other potentially-useful data structure: sets. A set represents an unordered collection of distinct elements. We can add and remove items from a set, but the set either contains the item or does not. Items in a set don’t have an index and are not counted.

    import java.util.Set;
    import java.util.HashSet;
    // set initialization
    Set<Integer> set = new HashSet<>();
    // adding items
    set.add(1);
    System.out.println(set);
    set.add(1);
    System.out.println(set);
    set.add(2);
    System.out.println(set);
    // membership testing
    System.out.println(set.contains(2));
    // set iteration
    for (Integer item : set) {
    System.out.println(item);
    }
    // item removal
    set.remove(1);

    Sets are generally less useful that lists or maps. But they do come in hand sometimes, particularly when you need to record membership but don’t care about counts or ordering. Let’s look at an example where a set might come in handy:

    import java.util.Set;
    import java.util.HashSet;
    String attendance = """
    Kermit,
    Gaffer,
    Gonzo,
    gonzo,
    Gonzo,
    Scooter,
    Waldorf,
    GONZO,
    Fozzie,
    Gaffer""";

    Homework: Word Lengths With Map

    Created By: Geoffrey Challen
    / Version: 2021.9.0

    Given a String containing words separated by the " " (space) character, write a method wordLengths that return a Map<String, Integer> mapping each word that is contained in the String to its length. assert that the passed String is not null.

    So, for example, given the String "Wow that is amazing", you would return a map with four mappings: "Wow" to 3, "that" to 4, "is" to 2, and "amazing" to 7.

    Note that you should not add any import statements, since both java.util.Map and java.util.HashMap are already available.

    More Practice

    Need more practice? Head over to the practice page.