This post is the continuation of Mapping composition in Java.
This time, I:
- Disallowed the nullvalues as the range value.
- Simplified the toStringmethod via using the streams.
Code
com.github.coderodde.mapping.Mapping.java:
package com.github.coderodde.mapping;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
 * This class implements a mapping from a domain set to a range set.
 * 
 * @param <D> the domain element type.
 * @param <R> the range element type.
 * 
 * @author Rodion "rodde" Efremov
 * @version 1.61 (Sep 14, 2023)
 * @since 1.6 (Sep 3, 2023)
 */
public final class Mapping<D, R> {
    final Map<D, R> data = new HashMap<>();
    
    public void map(D domainValue, R rangeValue) {
        checkDomainValueNotYetMapped(domainValue);
        Objects.requireNonNull(rangeValue,
                               "The range value is not allowed to be nul..");
        
        data.put(domainValue, rangeValue);
    }
    
    public boolean isMapped(D domainValue) {
        return data.containsKey(
                Objects.requireNonNull(
                        domainValue,
                        "The input domain value is null."));
    }
    
    public R map(D domainValue) {
        checkDomainValueIsMapped(domainValue);
        return data.get(domainValue);
    }
    
    @Override
    public String toString() {
        return data.entrySet()
                   .stream()
                   .map(Mapping::convertMapEntryToString)
                   .collect(Collectors.joining(", ", "[", "]"));
    }
    
    private static <D, R> 
        String convertMapEntryToString(Map.Entry<D, R> entry) {
        return new StringBuilder()
                    .append("(")
                    .append(entry.getKey())
                    .append(" -> ")
                    .append(entry.getValue())
                    .append(")").toString();
    }
    
    private void checkDomainValueNotYetMapped(D domainValue) {
        if (data.containsKey(
                Objects.requireNonNull(domainValue, "Domain value is null."))) {
            throw new DuplicateDomainValueException(
                    "Trying to map a domain value ["
                            + domainValue
                            + "] twice.");
        }
    }
    
    private void checkDomainValueIsMapped(D domainValue) {
        if (!data.containsKey(domainValue)) {
            throw new DomainValueIsNotMappedException(
                    "Domain value [" + domainValue + "] is not mapped.");
        }
    }
}
Critique request
As always, please tell me whatever comes to mind.
