SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Java Collections Framework
Exercise:
Exercises
Question:16 | ISBN:9780136091813 | Edition: 2

Question

Write a method called is1to1 that accepts a map whose keys and values are strings as its parameter and returns true if no two keys map to the same value. For example, {Marty=206–9024, Hawking=123–4567, Smith=949–0504,Newton=123–4567} should return false, but {Marty=206–9024, Hawking=555–1234, Smith=949–0504,Newton=123–4567} should return true. The empty map is considered 1-to-1 and returns true.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package collections;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class IsOneToOne {

     // this method takes map class as argument
    public static boolean is1To1(Map<String, String> map) {

     // check if map is null or whether if it is empty
        if (map == null || map.isEmpty())
            return true;
        Set<String> val = new HashSet<String>();

         // try to add the values of map in set class, if it failed to add
           // the value already exist and will return false otherwise true
        for (String value : map.values()) {
            boolean flag = val.add(value);
            if (!flag) {
                return false;
            }
            
        }
        return true;
    }

    public static void main(String args[]) {
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("kishore", "123");
        map1.put("william", "89");
        map1.put("vanila", "351");
        map1.put("marty", "123");

        // above map should return false
        boolean check = IsOneToOne.is1To1(map1);
        System.out.println(check);
        // below map should return true
        map1.put("kishore", "123");
        map1.put("william", "89");
        map1.put("vanila", "351");
        map1.put("marty", "12345");
        
        boolean check1 = IsOneToOne.is1To1(map1);
        System.out.println(check1);

    }
}
Output:

false
true

 

0 0

Discussions

Post the discussion to improve the above solution.