0
public static void main(String[] args) {
// write your code here
    LinkedHashMap<String,String>category1=new LinkedHashMap();

    category1.put("action","die hard");
    Scanner s=new Scanner(System.in);
    String answer=s.nextLine();
    if (category1.containsKey(answer))
        System.out.println(category1.get("action"));
    if (category1.containsValue(answer))
        System.out.println(category1.keySet());

How to get the key when the user answer with it's specific value, and how to add more values to one key?

  • "How to get the key when the user answer with it's specific value" and "how to get the key when the user answer with it's specific value" are two separate questions. Please [ask one question per post](https://meta.stackexchange.com/q/222735). – Pshemo Dec 24 '18 at 16:00
  • Anyway it looks like you need two maps: (1) `category -> [collection,of,movies]` (2) `movie->category`. – Pshemo Dec 24 '18 at 16:02

1 Answers1

2

1. The map collection, does not support multiple values under the same key, it will override whatever was stored there before.

2. However, you can change it from <String,String> to <String,List<String>>, thus gaining the ability to accumulate the answers from the client into the list. The key will refer to only one object, the list of Strings, but the list itself can hold many values.

3. In order to add more Strings to the list, you will need to retrieve the list by the desired key, and then add your new String to it.

Here is some code that implements the idea:

private void test(){
        Map<String, List<String>> categories = new HashMap<>();
        String answerFromClient = "Some text";
        List<String> actionAnswers = categories.get("action");
        if (actionAnswers == null){
            actionAnswers = new ArrayList<>();
            actionAnswers.add(answerFromClient);
            categories.put("action",actionAnswers);
        }
        else{
            actionAnswers.add(answerFromClient);
        }
    }
Daniel B.
  • 2,491
  • 2
  • 12
  • 23