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

1k views Asked by At

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));
1

There are 1 answers

0
WJS On BEST ANSWER

      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();
      }