java
16 lines · 5 steps
Building maps from lists with Collectors.toMap
Two stream pipelines turn a list of customers into id-keyed maps, one handling duplicate keys and ordering explicitly.
Explained by
highlit
1public Map<Long, CustomerDto> indexByCustomerId(List<CustomerDto> customers) {
2 return customers.stream()
3 .collect(Collectors.toMap(
4 CustomerDto::getId,
5 Function.identity(),
6 (existing, replacement) -> replacement,
7 LinkedHashMap::new));
8}
9
10public Map<Long, String> emailByCustomerId(List<CustomerDto> customers) {
11 return customers.stream()
12 .filter(c -> c.getEmail() != null)
13 .collect(Collectors.toMap(
14 CustomerDto::getId,
15 CustomerDto::getEmail));
16}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The two-argument `toMap` throws on duplicate keys, so supply a merge function whenever collisions are possible.
- 2`Function.identity()` keeps the whole element as the value, letting you index a list by any of its fields.
- 3Passing a map supplier like `LinkedHashMap::new` gives you control over iteration order and map type.
Related explainers
java
public final class CircuitBreaker { private enum State { CLOSED, OPEN, HALF_OPEN }
How a circuit breaker guards failing calls
state-machine
resilience
concurrency
Advanced
7 steps
java
@Service public class InventoryService { private final RestClient warehouseClient;
Bulkhead-protected HTTP calls in Spring
bulkhead
resilience
fallback
Intermediate
7 steps
java
@Configuration public class DataSourceLoggingConfig { @Bean
Wrapping a Spring DataSource for query tracing
proxy pattern
observability
data source
Intermediate
7 steps
java
@RestController @RequestMapping("/api/products") @Validated public class ProductSearchController {
Validating query params in a Spring controller
validation
pagination
rest-api
Intermediate
8 steps
java
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = PasswordsMatchValidator.class) public @interface PasswordsMatch {
Custom cross-field validation in Spring
bean-validation
custom-constraints
cross-field-validation
Intermediate
8 steps
java
public final class LogRedactor { private static final Pattern SECRET = Pattern.compile( "(?i)(password|token|api[_-]?key|secret|authorization)\\s*[=:]\\s*\\S+");
Streaming log redaction in Java
regex
streaming-io
try-with-resources
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-maps-from-lists-with-collectors-tomap-explained-java-3230/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.