In java, I want to search one or multiple words(one word or sentence) in a paragraph. I tried with contains() but it's not working properly in all the cases. Please help me to resolve the issue.
**Code:**
import java.io.*;
import java.nio.file.Paths;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter one word or multiple word to search: ");
String word = sc.next();
Map<String,String> searchResult = null;
try{System.out.println(getGlossaryFindWord(word));
searchResult = getGlossaryFindWord(word);
if(searchResult == null || searchResult.isEmpty()){
System.out.println("Search Not Found");
}
else{
for (Map.Entry<String, String> entry : searchResult.entrySet()) {
System.out.println(entry.getKey()+" : "+entry.getValue());
} }}
catch (IOException e){
e.printStackTrace();
}}
public static Map<String,String> getGlossaryFindWord(String word) throws IOException{
Map<String, String> responseMap = new HashMap();
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(Paths.get("C:/DevKit/glossary.json").toFile(), Map.class);
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(key.toLowerCase().contains(word.toLowerCase()) || value.toLowerCase().contains(word.toLowerCase())){
responseMap.put(entry.getKey(),entry.getValue());
}}
return responseMap;
}}
JSON File content: { "Formatting": "Formatting issues are the most contentious but the least consequential.", "Commentary": "Go provides C-style /* */ block comments and C++-style // line comments.", "Constants": "Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans", "Interfaces": "Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here", "Conversions": "The String method of Sequence is recreating the work that Sprint already does for slices.", "blankidentifier": "The blank identifier can be assigned or declared with any value of any type, with the value discarded harmlessly.", "Embedding": "Go does not provide the typical, type-driven notion of subclassing, but it does have the ability to “borrow” pieces of an implementation by embedding types within a struct or interface." }
Read more here: https://stackoverflow.com/questions/66343345/search-one-or-multiple-word-in-a-paragraph-in-java
Content Attribution
This content was originally published by Priyadharshini aj at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.