java
39 lines · 8 steps
Normalizing email addresses in Java
A validator that canonicalizes emails, applying Gmail's dot and plus-tag rules so equivalent addresses collapse to one form.
Explained by
highlit
1public final class EmailNormalizer {
2
3 private static final Pattern EMAIL_PATTERN = Pattern.compile(
4 "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
5 );
6
7 private static final Set<String> GMAIL_DOMAINS = Set.of("gmail.com", "googlemail.com");
8
9 public String normalize(String rawEmail) {
10 if (rawEmail == null || rawEmail.isBlank()) {
11 throw new InvalidEmailException("Email must not be empty");
12 }
13
14 String trimmed = rawEmail.strip().toLowerCase(Locale.ROOT);
15
16 if (!EMAIL_PATTERN.matcher(trimmed).matches()) {
17 throw new InvalidEmailException("Malformed email: " + rawEmail);
18 }
19
20 int at = trimmed.lastIndexOf('@');
21 String localPart = trimmed.substring(0, at);
22 String domain = trimmed.substring(at + 1);
23
24 if (GMAIL_DOMAINS.contains(domain)) {
25 int plus = localPart.indexOf('+');
26 if (plus >= 0) {
27 localPart = localPart.substring(0, plus);
28 }
29 localPart = localPart.replace(".", "");
30 domain = "gmail.com";
31 }
32
33 if (localPart.isEmpty()) {
34 throw new InvalidEmailException("Email local part is empty after normalization");
35 }
36
37 return localPart + "@" + domain;
38 }
39}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Normalizing to a canonical form lets you treat differently-typed inputs as one identity.
- 2Validate structure with a compiled pattern before slicing a string into meaningful parts.
- 3Provider-specific rules like Gmail's dot-insensitivity belong behind an explicit domain check.
Related explainers
java
@Component public class RegionCacheWarmer implements SmartInitializingSingleton { private static final Logger log = LoggerFactory.getLogger(RegionCacheWarmer.class);
Warming a Spring cache at startup
caching
startup-hook
dependency-injection
Intermediate
7 steps
python
import pandas as pd import numpy as np
Cleaning a customer DataFrame with pandas
data-cleaning
regex
normalization
Intermediate
9 steps
python
from datetime import date, timedelta from typing import Annotated from fastapi import APIRouter, Depends, Query
Validating date ranges with FastAPI dependencies
dependency-injection
validation
pydantic
Intermediate
6 steps
java
@RestController @RequestMapping("/api/products") @RequiredArgsConstructor public class ProductBatchController {
Batch JSON Merge Patch in Spring
json-merge-patch
rest-api
partial-update
Intermediate
8 steps
python
from collections.abc import MutableMapping class CaseInsensitiveDict(MutableMapping):
Building a case-insensitive dict in Python
data structures
abstract base classes
dunder methods
Intermediate
8 steps
java
public class TimedFetchService { private final ExecutorService executor = Executors.newFixedThreadPool(8); private final HttpClient httpClient = HttpClient.newHttpClient();
Enforcing HTTP timeouts with a Future
concurrency
timeouts
thread-pool
Intermediate
8 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/normalizing-email-addresses-in-java-explained-java-3d72/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.