/** * Copyright (C) 2019 Adrien Hopkins * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ package org.unitConverter.math; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * A "wrapper" for an existing map that treats a zero value as equivalent to null. * * @author Adrien Hopkins * @since 2019-10-16 * @param * type of key */ public final class ZeroIsNullMap extends AbstractMap { /** * Create a ZeroIsNullMap. This method always creates a new map. * * @param * type of key * @param map * map to input * @return map that treats zero as null * @throws NullPointerException * if map is null * @since 2019-10-16 */ public static Map create(final Map map) { return new ZeroIsNullMap<>(Objects.requireNonNull(map, "map must not be null.")); } private final Map map; /** * Creates the {@code ObjectProductMap}. * * @param map * @since 2019-10-16 */ private ZeroIsNullMap(final Map map) { this.map = map; } @Override public void clear() { this.map.clear(); } @Override public boolean containsKey(final Object key) { return this.map.containsKey(key) && this.map.get(key) != 0; } @Override public boolean containsValue(final Object value) { return this.values().contains(value); } @Override public Set> entrySet() { final Set> entrySet = new HashSet<>(this.map.entrySet()); entrySet.removeIf(e -> e.getValue() == 0); return entrySet; } @Override public Integer get(final Object key) { final Integer i = this.map.get(key); if (Objects.equals(i, 0)) return null; else return i; } @Override public Set keySet() { final Set keySet = new HashSet<>(this.map.keySet()); keySet.removeIf(k -> this.map.get(k) == 0); return keySet; } @Override public Integer put(final T key, final Integer value) { if (value != 0) return this.map.put(key, value); else return null; } @Override public void putAll(final Map m) { for (final T key : m.keySet()) { this.put(key, m.get(key)); } } @Override public Integer remove(final Object key) { return this.map.remove(key); } @Override public Collection values() { final List values = new ArrayList<>(this.map.values()); values.removeIf(i -> i == 0); return values; } }