Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.*;
- class Test
- {
- public static void main(String args[])
- {
- // MapWithAllUnique<Integer,Integer> map = new MapWithAllUnique<>();
- // map.put(1,1);
- // map.put(1,1);
- // map.put(1,2);
- // map.put(2,1);
- MapWithAllUnique<String,Integer> map = new MapWithAllUnique<>();
- map.put("a",1);
- map.put("b",2);
- System.out.println(map.isAllUnique());
- map.put("c",1);
- System.out.println(map.isAllUnique());
- map.put("a",3);
- System.out.println(map.isAllUnique());
- }
- }
- class MapWithAllUnique<K, V> {
- private final Map<K,V> values = new HashMap<>();
- private final Map<V, Integer> valuesCount = new HashMap<>();
- int counterNotUnique;
- public V put(K key, V value) {
- var oldValue = values.get(key); //1
- values.put(key, value);
- if (oldValue != null) {
- valuesCount.remove(oldValue);
- }
- int newCount = valuesCount.getOrDefault(value,0) + 1;
- if (newCount > 1) {
- counterNotUnique++;
- }
- valuesCount.put(value, newCount);
- return value;
- }
- public V get(K key) {
- return values.get(key);
- }
- public V remove(K key) {
- V removed = values.remove(key);
- int currenctCount = valuesCount.get(removed);
- if (currenctCount == 2) {
- counterNotUnique--;
- }
- valuesCount.put(values.get(key), valuesCount.get(removed) - 1);
- return removed;
- }
- public boolean isAllUnique() {
- return counterNotUnique <= 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement