javadictionarytestinghashmapinjective-function

How to check if a hashmap is Injective (OneOnOne) in Java?


How do i write a method that can check if a hashmap is Injective (OneOnOne)? So that there is only one key for every value in the map. I want it so it can pass this test:

    Map<Integer, Character> m = new HashMap<Integer, Character>();
    m.put(1, 'l');
    m.put(2, 'l');

    assertFalse(MapUtil.isOneOnOne(m));

Solution

  • 
          Map<Integer, Character> m = new HashMap<>();
          m.put(1, 'l');
          m.put(2, 'l');
          System.out.println(isOneToOne(m));
    
    
          public static boolean isOneToOne(Map<?, ?> map) {
             Set<?> set = new HashSet<>(map.values());
             return set.size() == map.keySet().size();
          }