Convert a Map to a List

A map offers three collections you can turn into a list: its keys, its values and its entries. Each is a live view of the map, so the first decision is whether to copy it. This page explains views versus copies, sorts and transforms entries into lists, shows the traps with entries and ordering, uses the Java 21 sequenced views, and compares the speed of the common copies.

Contents

Keys, values and entries are views

A Map is not a Collection, but it exposes three collections that are: keySet(), values() and entrySet(). None of them is a copy. Each is a view, a small object that reads from the map when you use it. Changes to the map show up in the view, and removing through the view removes from the map. Converting a map to a list therefore usually means copying one of these views into a new list.

The order of the resulting list is the map's iteration order: unspecified for HashMap, insertion order for LinkedHashMap, sorted for TreeMap. When a specific order matters and the map does not provide it, sort the list after copying.

Ways to get a list from a map
CodeSinceResultBest for
new ArrayList<>(map.keySet())Java 1.2Mutable copy of the keysKeys to sort or edit
new ArrayList<>(map.values())Java 1.2Mutable copy of the values, duplicates keptValues to process
new ArrayList<>(map.entrySet())Java 1.2Copy of live entry objectsSorting pairs
List.copyOf(map.values())Java 10Immutable copy; rejects nullRead-only snapshots
entrySet().stream()...toList()Java 16 (toList)Unmodifiable list of anythingSorting by value, mapping to objects
Map.Entry.copyOfJava 17Detached immutable entryEntries that must not change
sequencedKeySet(), reversed()Java 21Ordered views of sequenced mapsNewest first, last N entries

The examples ran on JDK 21. For the opposite direction, see converting a list to a map.

Copying keys, values and entries

A small stock map in a LinkedHashMap keeps the output order predictable, and one value is 0 so the program can remove it through a view.

Java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class KeysValuesEntries {

    public static void main(String[] args) {
        Map<String, Integer> stock = new LinkedHashMap<>();   // keeps insertion order
        stock.put("apple", 12);
        stock.put("pear", 0);
        stock.put("plum", 7);

        List<String> keys = new ArrayList<>(stock.keySet());
        List<Integer> values = new ArrayList<>(stock.values());
        List<Map.Entry<String, Integer>> entries = new ArrayList<>(stock.entrySet());

        System.out.println("keys:    " + keys);
        System.out.println("values:  " + values);
        System.out.println("entries: " + entries);

        // keySet() and values() are live views, not copies
        var view = stock.keySet();
        stock.put("fig", 3);
        System.out.println("view sees fig: " + view.contains("fig"));
        System.out.println("copy sees fig: " + keys.contains("fig"));

        // Removing from a view removes from the map
        stock.values().remove(0);
        System.out.println("after values().remove(0): " + stock);
    }
}

Output:

Output
keys:    [apple, pear, plum]
values:  [12, 0, 7]
entries: [apple=12, pear=0, plum=7]
view sees fig: true
copy sees fig: false
after values().remove(0): {apple=12, plum=7, fig=3}
  • Passing a view to the ArrayList constructor copies it once. The three lists hold the keys, the values and the Map.Entry objects, all in insertion order.
  • The view saw fig, added after it was obtained, but the copied list did not. Use a view when you want current contents, and a copy when you want a stable list or plan to change the map.
  • values().remove(0) removed the entry whose value was 0, pear, from the map itself. Views support removal but not addition: keySet().add throws UnsupportedOperationException.

Sorting, mapping and flattening

The quantities include a tie between apple and fig, so sorting by value needs a tie-breaker to be deterministic, and the map is created with Map.of, whose order is deliberately unpredictable.

Java
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SortedAndMapped {

    record Item(String name, int qty) {
    }

    public static void main(String[] args) {
        Map<String, Integer> stock = Map.of("apple", 12, "pear", 4, "plum", 7, "fig", 12);

        // Keys sorted by value, highest first, ties by key
        List<String> byQty = stock.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
                        .thenComparing(Map.Entry.comparingByKey()))
                .map(Map.Entry::getKey)
                .toList();
        System.out.println("by quantity: " + byQty);

        // Each entry turned into an object
        List<Item> items = stock.entrySet().stream()
                .map(e -> new Item(e.getKey(), e.getValue()))
                .sorted(Comparator.comparing(Item::name))
                .toList();
        System.out.println("items:       " + items);

        // Each entry turned into a string
        String report = stock.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(e -> e.getKey() + "=" + e.getValue())
                .collect(Collectors.joining(", "));
        System.out.println("report:      " + report);

        // Map of lists flattened into one list
        Map<String, List<String>> teams =
                Map.of("red", List.of("ann", "bo"), "blue", List.of("cy"));
        List<String> everyone = teams.values().stream().flatMap(List::stream).sorted().toList();
        System.out.println("flattened:   " + everyone);
    }
}

Output:

Output
by quantity: [apple, fig, plum, pear]
items:       [Item[name=apple, qty=12], Item[name=fig, qty=12], Item[name=pear, qty=4], Item[name=plum, qty=7]]
report:      apple=12, fig=12, pear=4, plum=7
flattened:   [ann, bo, cy]
  • Map.Entry.comparingByValue() and comparingByKey() are ready-made comparators. The explicit type witness <String, Integer> is needed before .reversed(), because Java cannot infer the types of a generic method when another method is chained onto it.
  • Mapping each entry to a record produces a list of real objects, which is easier to pass around than Map.Entry instances.
  • Joining mapped entries gives a report string; see joining strings.
  • For a map whose values are lists, flatMap(List::stream) merges them into one list. The flatMap page covers this in detail.

Top N, inverting, paging and filtering

Most map-to-list conversions in applications are reports: the top scorers, everyone with a given score, one page of results. The scores include ties on purpose, because ties are where report code goes wrong.

Java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class TopAndInvert {

    public static void main(String[] args) {
        Map<String, Integer> scores = new TreeMap<>(Map.of("ann", 91, "bob", 78, "cy", 91,
            "dee", 64, "ed", 85, "flo", 78));

        // Top 3 by score, ties broken by name
        List<String> top3 = scores.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder())
                .thenComparing(Map.Entry.comparingByKey()))
            .limit(3)
            .map(e -> e.getKey() + " (" + e.getValue() + ")")
            .toList();
        System.out.println("top 3:        " + top3);

        // Invert: score -> list of names with that score
        Map<Integer, List<String>> byScore = scores.entrySet().stream()
            .collect(Collectors.groupingBy(Map.Entry::getValue, TreeMap::new,
                Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
        System.out.println("inverted:     " + byScore);

        // A page of results: skip and limit on a sorted key list
        List<String> names = new ArrayList<>(scores.keySet());
        int page = 1;
        int size = 2;
        System.out.println("page 1 (0-based), size 2: "
            + names.stream().skip((long) page * size).limit(size).toList());
        System.out.println("same with subList:        "
            + names.subList(page * size, Math.min(names.size(), (page + 1) * size)));

        // Keys whose value passes a test
        List<String> passed = scores.entrySet().stream().filter(e -> e.getValue() >= 80)
            .map(Map.Entry::getKey).toList();
        System.out.println("80 or more:   " + passed);

        // Rows for a table or JSON array: one small map per entry
        List<Map<String, Object>> rows = scores.entrySet().stream().limit(2)
            .map(e -> Map.<String, Object>of("name", e.getKey(), "score", e.getValue()))
            .map(TreeMap::new)
            .collect(Collectors.toList());
        System.out.println("rows:         " + rows);
    }
}

Output:

Output
top 3:        [ann (91), cy (91), ed (85)]
inverted:     {64=[dee], 78=[bob, flo], 85=[ed], 91=[ann, cy]}
page 1 (0-based), size 2: [cy, dee]
same with subList:        [cy, dee]
80 or more:   [ann, cy, ed]
rows:         [{name=ann, score=91}, {name=bob, score=78}]
  • Sorting by value in reverse with a name tie-breaker, then limit(3), gives the top three. ann and cy both have 91; without the tie-breaker, their order would depend on the map.
  • Inverting a map cannot produce a map with single values, because several keys can share a value. groupingBy(getValue, mapping(getKey, toList())) collects the names per score, so 78 maps to bob and flo.
  • skip and limit on a stream, or subList on a list, return one page. subList is a view of the list and throws if the end is past the size, hence the Math.min.
  • Filtering entries by value and keeping the keys answers questions such as "who scored 80 or more".
  • Turning each entry into a small map gives rows ready for a JSON array or a template. Map.of has no fixed order, so each row is copied into a TreeMap for stable output.

Traps with entries and order

Entries look like simple pairs, but those from entrySet belong to the map. The program also shows what HashMap does to order and how duplicates behave in values().

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class EntryTraps {

    public static void main(String[] args) {
        Map<String, Integer> stock = new TreeMap<>(Map.of("apple", 12, "pear", 4));

        // Entries from entrySet are live: setValue writes into the map
        List<Map.Entry<String, Integer>> entries = new ArrayList<>(stock.entrySet());
        entries.get(0).setValue(99);
        System.out.println("after setValue on a list entry: " + stock);

        // Map.Entry.copyOf (Java 17) makes a detached, immutable copy
        List<Map.Entry<String, Integer>> copies = stock.entrySet().stream()
            .map(Map.Entry::copyOf).toList();
        stock.put("apple", 1);
        System.out.println("copy keeps:  " + copies.get(0) + ", map now: " + stock);
        try {
            copies.get(0).setValue(5);
        } catch (UnsupportedOperationException e) {
            System.out.println("copy.setValue: UnsupportedOperationException");
        }

        // Map.entry(k, v) (Java 9) creates a standalone immutable pair
        Map.Entry<String, Integer> pair = Map.entry("fig", 3);
        System.out.println("Map.entry: " + pair.getKey() + " -> " + pair.getValue());

        // HashMap order is not insertion order
        Map<String, Integer> hash = new HashMap<>();
        for (String k : List.of("zeta", "alpha", "omega", "kappa", "beta")) {
            hash.put(k, k.length());
        }
        System.out.println("HashMap keys: " + new ArrayList<>(hash.keySet())
            + " (inserted zeta, alpha, omega, kappa, beta)");

        // values() may contain duplicates; keySet() never does
        Map<String, String> owners = Map.of("a.txt", "ann", "b.txt", "bob", "c.txt", "ann");
        System.out.println("values size " + owners.values().size() + ", distinct "
            + owners.values().stream().distinct().count());
    }
}

Output:

Output
after setValue on a list entry: {apple=99, pear=4}
copy keeps:  apple=99, map now: {apple=1, pear=4}
copy.setValue: UnsupportedOperationException
Map.entry: fig -> 3
HashMap keys: [zeta, alpha, kappa, omega, beta] (inserted zeta, alpha, omega, kappa, beta)
values size 3, distinct 2
  • Copying the entry set copies references to the map's own entry objects. Calling setValue on an entry in the list changed apple to 99 in the map. Code that stores such lists for later can change the map by accident, or see values change underneath it.
  • Map.Entry.copyOf, added in Java 17, makes detached immutable entries. The copy kept 99 after the map changed, and setValue on it throws.
  • Map.entry(key, value), from Java 9, creates a standalone immutable pair, useful for building lists of pairs.
  • The HashMap returned its keys in an order unrelated to insertion: kappa came before omega. That order can also change when the map grows. Use LinkedHashMap or sort the list.
  • values() can contain duplicates, here ann twice; keySet() never does.

Sequenced maps, and the cost of copying

Java 21 made ordered maps SequencedMaps, with reversible views and direct access to the ends. The second half of the program copies a million values into a list five ways and keeps the fastest of three runs.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

public class SequencedAndSpeed {

    public static void main(String[] args) {
        // Java 21: sequenced views of a LinkedHashMap or TreeMap
        LinkedHashMap<String, Integer> recent = new LinkedHashMap<>();
        recent.put("first", 1);
        recent.put("second", 2);
        recent.put("third", 3);
        System.out.println("newest first: " + new ArrayList<>(recent.sequencedKeySet().reversed()));
        System.out.println("firstEntry:   " + recent.firstEntry() + ", lastEntry: "
            + recent.lastEntry());
        System.out.println("values reversed: " + recent.sequencedValues().reversed());

        // Speed of copying a large map's values into a list
        Map<Integer, String> big = new HashMap<>();
        for (int i = 0; i < 1000000; i++) {
            big.put(i, "v" + i);
        }
        System.out.printf("copy %,d values into a list%n", big.size());
        time("new ArrayList<>(map.values())", () -> new ArrayList<>(big.values()));
        time("map.values().stream().toList()", () -> big.values().stream().toList());
        time("List.copyOf(map.values())", () -> List.copyOf(big.values()));
        time("forEach + add", () -> {
            List<String> out = new ArrayList<>();
            big.forEach((k, v) -> out.add(v));
            return out;
        });
        time("entrySet stream map(getValue)", () -> big.entrySet().stream()
            .map(Map.Entry::getValue).toList());
    }

    // Best of 3 runs
    static void time(String name, Supplier<List<String>> f) {
        long best = Long.MAX_VALUE;
        int size = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            size = f.get().size();
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("  %-32s %6.1f ms  (%,d)%n", name, best / 1e6, size);
    }
}

Output (approximate times; 2-CPU Linux machine, JDK 21):

Output
newest first: [third, second, first]
firstEntry:   first=1, lastEntry: third=3
values reversed: [3, 2, 1]
copy 1,000,000 values into a list
  new ArrayList<>(map.values())      21.9 ms  (1,000,000)
  map.values().stream().toList()     20.8 ms  (1,000,000)
  List.copyOf(map.values())          26.6 ms  (1,000,000)
  forEach + add                      32.9 ms  (1,000,000)
  entrySet stream map(getValue)      23.0 ms  (1,000,000)
  • sequencedKeySet().reversed() gave the keys newest first without sorting or index arithmetic. firstEntry and lastEntry read the ends, and sequencedValues().reversed() reverses the values. TreeMap supports the same methods.
  • All copies took a few tens of milliseconds for a million values; the differences between them were small and changed from run to run. new ArrayList<>(values()) and stream().toList() both size the result from the collection once.
  • List.copyOf also checks every element for null, and a forEach with add grows the list step by step, which made them slightly slower here. Choose by the kind of result you need: mutable, unmodifiable or immutable.

Arrays, primitive values and other list types

A "list" is not always a java.util.List. Older APIs want arrays, numeric code wants primitives, and some callers need a particular list class. The stock map has three entries with one zero, small enough to print every result.

Java
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ArraysAndPrimitives {

    public static void main(String[] args) {
        Map<String, Integer> stock = new LinkedHashMap<>();
        stock.put("apple", 12);
        stock.put("pear", 0);
        stock.put("plum", 30);

        // Arrays: toArray(IntFunction) since Java 11, or toArray(new T[0])
        String[] keys = stock.keySet().toArray(String[]::new);
        Integer[] boxed = stock.values().toArray(new Integer[0]);
        System.out.println("String[]:  " + Arrays.toString(keys));
        System.out.println("Integer[]: " + Arrays.toString(boxed));

        // Primitive values: no boxing in the result, and sums or stats come for free
        int[] amounts = stock.values().stream().mapToInt(Integer::intValue).toArray();
        System.out.println("int[]:     " + Arrays.toString(amounts) + ", sum "
                + Arrays.stream(amounts).sum());
        System.out.println("statistics: " + stock.values().stream()
                .mapToInt(Integer::intValue).summaryStatistics());

        // A specific List type
        LinkedList<String> queue = stock.keySet().stream()
                .collect(Collectors.toCollection(LinkedList::new));
        System.out.println("LinkedList: " + queue + ", first " + queue.getFirst());

        // A list of keys and values interleaved, as some APIs expect
        List<Object> flat = stock.entrySet().stream()
                .<Object>flatMap(e -> Stream.of(e.getKey(), e.getValue())).toList();
        System.out.println("interleaved: " + flat);

        // And back again: a list of entries into a map, keeping the order
        List<Map.Entry<String, Integer>> entries = List.copyOf(stock.entrySet());
        Map<String, Integer> back = entries.stream()
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (a, b) -> a, LinkedHashMap::new));
        System.out.println("list of entries back to a map equals the original: "
                + back.equals(stock));

        // The old trap: toArray() without an argument returns Object[]
        Object[] untyped = stock.keySet().toArray();
        try {
            String[] cast = (String[]) untyped;
            System.out.println(cast.length);
        } catch (ClassCastException e) {
            System.out.println("(String[]) keySet().toArray(): ClassCastException");
        }
    }
}

Output:

Output
String[]:  [apple, pear, plum]
Integer[]: [12, 0, 30]
int[]:     [12, 0, 30], sum 42
statistics: IntSummaryStatistics{count=3, sum=42, min=0, average=14.000000, max=30}
LinkedList: [apple, pear, plum], first apple
interleaved: [apple, 12, pear, 0, plum, 30]
list of entries back to a map equals the original: true
(String[]) keySet().toArray(): ClassCastException
  • toArray(String[]::new), added to Collection in Java 11, creates a correctly typed array. toArray(new Integer[0]) is the older form and works on any version.
  • mapToInt(Integer::intValue).toArray() produced an int[] without a wrapper object per element, and summaryStatistics() gave count, sum, minimum, average and maximum in one pass.
  • Collectors.toCollection(LinkedList::new) chooses the list class, here a LinkedList to use as a queue.
  • A key-value-key-value list, which some logging and query APIs expect, takes a flatMap to Stream.of(key, value). The type witness <Object> tells the compiler that the mixed stream is a stream of Object.
  • A list of entries goes back into a map with Collectors.toMap, passing LinkedHashMap::new to keep the order; the result equalled the original map. More on converting a list to a map.
  • toArray() without an argument returns an Object[], and casting it to String[] threw ClassCastException, even though every element is a string. The array's own type is Object[].

Parallel lists and maps that change during the copy

A common shortcut is to copy the keys into one list and the values into another and match them by index. That only works if the map does not change between the two copies. The program changes the map in between, as another method or thread might, and then copies a ConcurrentHashMap while a second thread is still adding to it.

Java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ParallelListsTrap {

    record Price(String item, int cents) { }

    public static void main(String[] args) throws Exception {
        Map<String, Integer> prices = new LinkedHashMap<>();
        prices.put("apple", 120);
        prices.put("bread", 250);
        prices.put("cheese", 900);

        // Two separate copies: fine only while nothing changes between them
        List<String> names = new ArrayList<>(prices.keySet());
        prices.remove("apple");                                 // something changes in between
        prices.put("dates", 400);
        List<Integer> amounts = new ArrayList<>(prices.values());
        for (int i = 0; i < names.size(); i++) {
            System.out.println("  " + names.get(i) + " -> " + amounts.get(i));
        }
        System.out.println("names " + names + " no longer line up with amounts " + amounts);

        // One copy of the entries keeps each key with its own value
        List<Price> rows = prices.entrySet().stream()
                .map(e -> new Price(e.getKey(), e.getValue()))
                .toList();
        System.out.println("one pass over entrySet: " + rows);

        // ConcurrentHashMap: copying while another thread writes never throws,
        // but the copy is a mix of before and after (weakly consistent)
        Map<Integer, Integer> live = new ConcurrentHashMap<>();
        for (int i = 0; i < 100000; i++) {
            live.put(i, i);
        }
        Thread writer = Thread.ofPlatform().start(() -> {
            for (int i = 100000; i < 200000; i++) {
                live.put(i, i);
            }
        });
        List<Integer> snapshot = new ArrayList<>(live.values());
        writer.join();
        System.out.println("copy taken during writes: between 100,000 and 200,000 values: "
                + (snapshot.size() >= 100000 && snapshot.size() <= 200000)
                + ", map size now " + live.size());
    }
}

Output:

Output
apple -> 250
  bread -> 900
  cheese -> 400
names [apple, bread, cheese] no longer line up with amounts [250, 900, 400]
one pass over entrySet: [Price[item=bread, cents=250], Price[item=cheese, cents=900], Price[item=dates, cents=400]]
copy taken during writes: between 100,000 and 200,000 values: true, map size now 200000
  • The keys were copied before apple was removed and dates added, and the values after. Matching by index then paired apple with bread's price 250 and cheese with the price of dates, 400. Nothing failed; the data was simply wrong.
  • Copying the entries once, here into records, keeps every key with its own value: the result has bread, cheese and dates with their correct prices.
  • Copying the values of a ConcurrentHashMap while another thread was writing did not throw. The copy held somewhere between the 100,000 values that existed at the start and the 200,000 at the end: the views are weakly consistent, reflecting some of the concurrent changes. A HashMap copied while another thread writes to it can instead throw ConcurrentModificationException or produce a corrupt result, as the ConcurrentHashMap page explains.

Which approach to use

Choosing a map-to-list conversion
You needUse
The keys as a listnew ArrayList<>(map.keySet())
The values as a listnew ArrayList<>(map.values())
A read-only snapshotList.copyOf(map.values()) (no nulls allowed)
Keys sorted by valueentrySet().stream().sorted(comparingByValue())
Pairs that will not change with the mapmap(Map.Entry::copyOf) or map to a record
Objects built from entriesentrySet().stream().map(e -> new Item(...))
One list from a map of listsvalues().stream().flatMap(List::stream)
Newest or last entries firstLinkedHashMap with sequencedKeySet().reversed()
Current contents without copyingUse the view directly
A typed arraykeySet().toArray(String[]::new)
Primitive numbersvalues().stream().mapToInt(Integer::intValue).toArray()
Keys and values that must stay matchedOne pass over entrySet(), never two separate copies

To iterate over a map without building a list, see looping through a map.