Programming
Data Structures
Maps
Value Retrieval
Code Examples

SELECT Specific Value from map

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Selecting a specific value from a map can mean two different things: looking up a value by a known key, or searching the map for an entry whose key or value matches some condition. Those are very different operations, and the cleanest code depends on which one you actually need.

Case 1: You Already Know the Key

If the key is known, a map lookup is the direct and efficient answer. In Java, that is simply get(...).

java
1import java.util.Map;
2
3public class MapLookupDemo {
4    public static void main(String[] args) {
5        Map<String, Integer> scores = Map.of(
6            "alice", 95,
7            "bob", 82,
8            "carol", 91
9        );
10
11        Integer aliceScore = scores.get("alice");
12        System.out.println(aliceScore);
13    }
14}

This is the normal purpose of a map: fast retrieval by key.

Handle Missing Keys Deliberately

A common mistake is assuming the key must be present. If it might be missing, use containsKey(...) or getOrDefault(...).

java
1import java.util.HashMap;
2import java.util.Map;
3
4public class MapDefaultDemo {
5    public static void main(String[] args) {
6        Map<String, Integer> scores = new HashMap<>();
7        scores.put("alice", 95);
8
9        int value = scores.getOrDefault("dave", 0);
10        System.out.println(value);
11    }
12}

This avoids null-handling surprises when absence is a normal case.

Case 2: You Need to Search by a Condition

Sometimes you do not know the key. Instead, you want the first entry whose value matches some rule. Then you must iterate or stream over the entries.

java
1import java.util.LinkedHashMap;
2import java.util.Map;
3import java.util.Optional;
4
5public class MapSearchDemo {
6    public static void main(String[] args) {
7        Map<String, Integer> scores = new LinkedHashMap<>();
8        scores.put("alice", 95);
9        scores.put("bob", 82);
10        scores.put("carol", 91);
11
12        Optional<Integer> selected = scores.entrySet().stream()
13            .filter(entry -> entry.getKey().startsWith("c"))
14            .map(Map.Entry::getValue)
15            .findFirst();
16
17        System.out.println(selected.orElse(-1));
18    }
19}

This is no longer a constant-time map lookup, because you are scanning for a predicate match.

Selecting Both Key and Value

Often the value alone is not enough. You may want the entry so you can keep the associated key.

java
1import java.util.LinkedHashMap;
2import java.util.Map;
3import java.util.Optional;
4
5public class MapEntryDemo {
6    public static void main(String[] args) {
7        Map<String, Integer> scores = new LinkedHashMap<>();
8        scores.put("alice", 95);
9        scores.put("bob", 82);
10        scores.put("carol", 91);
11
12        Optional<Map.Entry<String, Integer>> match = scores.entrySet().stream()
13            .filter(entry -> entry.getValue() > 90)
14            .findFirst();
15
16        match.ifPresent(entry ->
17            System.out.println(entry.getKey() + " -> " + entry.getValue())
18        );
19    }
20}

Returning the entry keeps more context and is often more useful than returning just the value.

If Many Searches Use the Same Secondary Rule

If you keep searching a map by value or by some derived property, the map may be the wrong structure for that access pattern. Maps are optimized for key-based access. Repeated full scans suggest you may need:

  • a second index
  • a reversed map
  • a list plus filtering
  • a more specialized data structure

Choosing the right structure matters more than writing clever retrieval code.

Null and Duplicate Considerations

Some map types allow null values, and different keys can map to the same value. That means "select value X" may return:

  • no result
  • one result
  • several matching entries

Be explicit about which case you want. findFirst() gives one match, but it does not prove uniqueness.

Common Pitfalls

The biggest mistake is confusing direct lookup with predicate search. map.get(key) is fast because it uses the key; filtering entries is a scan.

Another issue is ignoring missing-key behavior. A map lookup that returns null is not automatically an error; it may simply mean the key is absent.

Developers also sometimes search by value repeatedly and wonder why performance is poor. If the access pattern is not key-based, reconsider the data structure.

Finally, if duplicate values are possible, do not assume there is only one matching entry unless your domain model guarantees it.

Summary

  • Use get(...) or getOrDefault(...) when the key is known.
  • Search entrySet() when you need to select by a condition instead of by key.
  • Return a full entry when you need both key and value.
  • Repeated scans may indicate the map is the wrong structure for the real query pattern.
  • Be explicit about missing keys and duplicate matching values.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.