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 Copying keys, values and entries Sorting, mapping and flattening Top N, inverting, paging and filtering Traps with entries and order Sequenced maps, and the cost of copying Arrays, primitive values and other list types Parallel lists and maps that change during the copy Which approach to use
Keys, values and entries are views
A MapCollectionkeySet()values()entrySet()
The order of the resulting list is the map's iteration order: unspecified for HashMapLinkedHashMapTreeMap
| Code | Since | Result | Best for |
|---|---|---|---|
new ArrayList<>(map.keySet()) | Java 1.2 | Mutable copy of the keys | Keys to sort or edit |
new ArrayList<>(map.values()) | Java 1.2 | Mutable copy of the values, duplicates kept | Values to process |
new ArrayList<>(map.entrySet()) | Java 1.2 | Copy of live entry objects | Sorting pairs |
List.copyOf(map.values()) | Java 10 | Immutable copy; rejects null | Read-only snapshots |
entrySet().stream()...toList() | Java 16 (toList | Unmodifiable list of anything | Sorting by value, mapping to objects |
Map.Entry.copyOf | Java 17 | Detached immutable entry | Entries that must not change |
sequencedKeySet()reversed() | Java 21 | Ordered views of sequenced maps | Newest first, last N entries |
The examples ran on JDK 21. For the opposite direction, see
Copying keys, values and entries
A small stock map in a LinkedHashMap
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:
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
constructor copies it once. The three lists hold the keys, the values and theArrayList objects, all in insertion order.Map.Entry - The view saw
, 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.fig removed the entry whose value was 0,values().remove(0) , from the map itself. Views support removal but not addition:pear throwskeySet().add .UnsupportedOperationException
Sorting, mapping and flattening
The quantities include a tie between applefigMap.of
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:
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]
andMap.Entry.comparingByValue() are ready-made comparators. The explicit type witnesscomparingByKey() is needed before<String, Integer> , because Java cannot infer the types of a generic method when another method is chained onto it..reversed()- Mapping each entry to a record produces a list of real objects, which is easier to pass around than
instances.Map.Entry - Joining mapped entries gives a report string; see
joining strings . - For a map whose values are lists,
merges them into one list. TheflatMap(List::stream)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.
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:
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
, gives the top three.limit(3) andann both have 91; without the tie-breaker, their order would depend on the map.cy - Inverting a map cannot produce a map with single values, because several keys can share a value.
collects the names per score, so 78 maps togroupingBy(getValue, mapping(getKey, toList())) andbob .flo andskip on a stream, orlimit on a list, return one page.subList is a view of the list and throws if the end is past the size, hence thesubList .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.
has no fixed order, so each row is copied into aMap.of for stable output.TreeMap
Traps with entries and order
Entries look like simple pairs, but those from entrySetHashMapvalues()
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:
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
on an entry in the list changedsetValue to 99 in the map. Code that stores such lists for later can change the map by accident, or see values change underneath it.apple , added in Java 17, makes detached immutable entries. The copy kept 99 after the map changed, andMap.Entry.copyOf on it throws.setValue , from Java 9, creates a standalone immutable pair, useful for building lists of pairs.Map.entry(key, value)- The
returned its keys in an order unrelated to insertion:HashMap came beforekappa . That order can also change when the map grows. Useomega or sort the list.LinkedHashMap can contain duplicates, herevalues() twice;ann never does.keySet()
Sequenced maps, and the cost of copying
Java 21 made ordered maps SequencedMap
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):
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)
gave the keys newest first without sorting or index arithmetic.sequencedKeySet().reversed() andfirstEntry read the ends, andlastEntry reverses the values.sequencedValues().reversed() supports the same methods.TreeMap- All copies took a few tens of milliseconds for a million values; the differences between them were small and changed from run to run.
andnew ArrayList<>(values()) both size the result from the collection once.stream().toList() also checks every element for null, and aList.copyOf withforEach grows the list step by step, which made them slightly slower here. Choose by the kind of result you need: mutable, unmodifiable or immutable.add
Arrays, primitive values and other list types
A "list" is not always a java.util.List
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:
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
, added totoArray(String[]::new) in Java 11, creates a correctly typed array.Collection is the older form and works on any version.toArray(new Integer[0]) produced anmapToInt(Integer::intValue).toArray() without a wrapper object per element, andint[] gave count, sum, minimum, average and maximum in one pass.summaryStatistics() chooses the list class, here aCollectors.toCollection(LinkedList::new) to use as a queue.LinkedList- A key-value-key-value list, which some logging and query APIs expect, takes a
toflatMap . The type witnessStream.of(key, value) tells the compiler that the mixed stream is a stream of<Object> .Object - A list of entries goes back into a map with
, passingCollectors.toMap to keep the order; the result equalled the original map. More onLinkedHashMap::newconverting a list to a map . without an argument returns antoArray() , and casting it toObject[] threwString[] , even though every element is a string. The array's own type isClassCastException .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
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:
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
was removed andapple added, and the values after. Matching by index then paireddates with bread's price 250 andapple with the price of dates, 400. Nothing failed; the data was simply wrong.cheese - 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
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. AConcurrentHashMap copied while another thread writes to it can instead throwHashMap or produce a corrupt result, as theConcurrentModificationExceptionConcurrentHashMap page explains.
Which approach to use
| You need | Use |
|---|---|
| The keys as a list | new ArrayList<>(map.keySet()) |
| The values as a list | new ArrayList<>(map.values()) |
| A read-only snapshot | List.copyOf(map.values()) |
| Keys sorted by value | entrySet().stream().sorted(comparingByValue()) |
| Pairs that will not change with the map | map(Map.Entry::copyOf) |
| Objects built from entries | entrySet().stream().map(e -> new Item(...)) |
| One list from a map of lists | values().stream().flatMap(List::stream) |
| Newest or last entries first | LinkedHashMapsequencedKeySet().reversed() |
| Current contents without copying | Use the view directly |
| A typed array | keySet().toArray(String[]::new) |
| Primitive numbers | values().stream().mapToInt(Integer::intValue).toArray() |
| Keys and values that must stay matched | One pass over entrySet() |
To iterate over a map without building a list, see