Aleksey Potapov
Aleksey Potapov

Reputation: 3783

String compare with keys in Map in Java

I have a collection Map as (String,String), and the String inputText. What could you recommend to scan the inputText to check, if it contains any key from Map.

E.g. I have the next:

    //hashmap is used - I don't need the order
    Map<String, String> mapOfStrings = new HashMap<String,String>();
    mapOfStrings.put("java","yep, java is very useful!");
    mapOfStrings.put("night","night coding is the routine");

    String inputText =  "what do you think about java?"
    String outputText = ""; //here should be an <answer>
    Set<String> keys = mapOfStrings.keySet();
    for (String key:keys){
        String value = mapOfStrings.get(key);
        //here it must uderstand, that the inputText contains "java" that equals to
        //the key="java" and put in outputText the correspondent value
    }

All I know, it's not the equals() or compareTo(). May be I should somehow check the order of characters in inptuText?

Regards

Upvotes: 0

Views: 9785

Answers (1)

Vishal K
Vishal K

Reputation: 13066

You can use the following:

for (String key:keys){
        String value = mapOfStrings.get(key);
        //here it must uderstand, that the inputText contains "java" that equals to
        //the key="java" and put in outputText the correspondent value
        if (inputText.contains(key))
        {
           outputText = value;
        }
    }

Upvotes: 3

Related Questions