toMap, joining, and summarizing
Convert streams to maps, concatenate strings with joining, and compute stats with summarizingInt.
toMap, joining, and summarizing is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Collectors.toMap Basics
Collectors.toMap(keyMapper, valueMapper) converts a stream to a Map. Each element provides one key-value pair.
import java.util.*;
import java.util.stream.*;
record Country(String code, String name) {}
List<Country> countries = List.of(
new Country("US","United States"),
new Country("DE","Germany"),
new Country("JP","Japan")
);
Map<String, String> codeToName =
countries.stream().collect(
Collectors.toMap(Country::code, Country::name)
);
System.out.println(codeToName.get("DE")); // GermanyHandling Duplicate Keys
toMap throws IllegalStateException on duplicate keys. Supply a merge function as the third argument to resolve conflicts:
List<String> words = List.of("apple","ant","banana","bat","cherry");
Map<Character, String> firstByLetter =
words.stream().collect(
Collectors.toMap(
w -> w.charAt(0),
w -> w,
(existing, replacement) -> existing // keep first
)
);
System.out.println(firstByLetter); // {a=apple, b=banana, c=cherry}toMap with value transformation
The value mapper can be any function — transform the element before storing:
record User(String login, String email) {}
List<User> users = List.of(
new User("alice","alice@example.com"),
new User("bob","bob@example.com")
);
Map<String, String> loginToEmail =
users.stream().collect(
Collectors.toMap(User::login, u -> u.email().toUpperCase())
);
System.out.println(loginToEmail.get("alice")); // ALICE@EXAMPLE.COMtoUnmodifiableMap
Use Collectors.toUnmodifiableMap() to produce an immutable map — equivalent to wrapping with Collections.unmodifiableMap() but cleaner:
Map<String, Integer> wordLengths =
Stream.of("Java","Stream","API")
.collect(Collectors.toUnmodifiableMap(w -> w, String::length));
// wordLengths.put("test",4); // throws UnsupportedOperationExceptionCollectors.joining
Collectors.joining() concatenates string elements. It accepts optional delimiter, prefix, and suffix:
List<String> names = List.of("Alice","Bob","Carol");
System.out.println(names.stream().collect(Collectors.joining()));
// AliceBobCarol
System.out.println(names.stream().collect(Collectors.joining(", ")));
// Alice, Bob, Carol
System.out.println(names.stream().collect(Collectors.joining(", ", "[", "]")));
// [Alice, Bob, Carol]joining for CSV Output
Build CSV rows or SQL IN clauses with joining:
List<Integer> ids = List.of(1,2,3,4,5);
String inClause = ids.stream()
.map(Object::toString)
.collect(Collectors.joining(",", "(", ")"));
System.out.println("WHERE id IN " + inClause);
// WHERE id IN (1,2,3,4,5)summarizingInt / Long / Double
Collectors.summarizingInt() computes all statistics in one pass and returns an IntSummaryStatistics:
record Product(String name, int price) {}
List<Product> products = List.of(
new Product("A",100), new Product("B",200), new Product("C",150)
);
IntSummaryStatistics stats =
products.stream().collect(Collectors.summarizingInt(Product::price));
System.out.println("Count: " + stats.getCount()); // 3
System.out.println("Sum: " + stats.getSum()); // 450
System.out.println("Min: " + stats.getMin()); // 100
System.out.println("Max: " + stats.getMax()); // 200
System.out.println("Avg: " + stats.getAverage()); // 150.0summingInt and averagingInt
For simpler cases where you only need one statistic:
int total = products.stream().collect(Collectors.summingInt(Product::price));
System.out.println("Total: " + total); // 450
double avg = products.stream().collect(Collectors.averagingInt(Product::price));
System.out.println("Average: " + avg); // 150.0groupingBy with summarizingInt
Combine summarization per group:
record Sale(String region, int amount) {}
List<Sale> sales = List.of(
new Sale("North",100), new Sale("South",200),
new Sale("North",150), new Sale("South",300)
);
Map<String, IntSummaryStatistics> statsByRegion =
sales.stream().collect(
Collectors.groupingBy(Sale::region,
Collectors.summarizingInt(Sale::amount))
);
statsByRegion.forEach((r,s) ->
System.out.printf("%s: sum=%d avg=%.1f%n", r, s.getSum(), s.getAverage()));Collecting to LinkedHashMap
By default toMap produces a HashMap (unordered). Use the 4-arg overload to specify a LinkedHashMap for insertion-order preservation:
Map<String, Integer> ordered =
Stream.of("banana","apple","cherry")
.collect(Collectors.toMap(
w -> w,
String::length,
(a,b) -> a,
LinkedHashMap::new
));
System.out.println(ordered.keySet()); // [banana, apple, cherry]Practical: Config Parser
Parse key=value lines into a map with toMap:
List<String> lines = List.of("host=localhost","port=5432","db=myapp");
Map<String, String> config =
lines.stream()
.map(l -> l.split("=", 2))
.collect(Collectors.toMap(a -> a[0], a -> a[1]));
System.out.println(config.get("port")); // 5432Quick Check
You use Collectors.toMap(k, v) on a stream that contains two elements with the same key. What happens?
Recap: toMap, joining, summarizing
Key takeaways:
- toMap(keyMapper, valueMapper) — throws on duplicate keys without merge fn
- joining(delimiter, prefix, suffix) — concatenates strings elegantly
- summarizingInt gives count+sum+min+max+avg in one pass
- summingInt/averagingInt for single-statistic needs
- Use 4-arg toMap with LinkedHashMap::new for ordered results
Frequently asked questions
Is the “toMap, joining, and summarizing” lesson free?
Yes — the full text of “toMap, joining, and summarizing” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “toMap, joining, and summarizing”?
Convert streams to maps, concatenate strings with joining, and compute stats with summarizingInt. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “toMap, joining, and summarizing” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- groupingBy: Classifying Elements
- partitioningBy and counting
- toMap, joining, and summarizing
- Building a Custom Collector