Correct usage of Hashmaps for synonyms - java

I am trying to store synonyms of a given word into a HashMap. I then take the user input and check to see if it is a word or its synonym. For example, suppose the main word is "bank" and its synonmyns are "safe","tresury" and "credit union". If the user enters "bank", I want to output the word "bank". If the user enters " safe", I still want to output the word "bank" because "safe" is a synonym of "bank".
Here is my Synonymn method
public static void populateSynonymMap() {
HashMap<String, String[]> synonymMap = new HashMap<String, String[]>();
String word = "bank";
String synonymn[] = { "safe", "treasury", "credit union" };
synonymMap.put(word, synonymn);
}
and here is my main method
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
List<String> matches = new ArrayList<String>();
HashMap<String, String[]> synonymMap = new HashMap<String, String[]>();
synonmynMap = populateSynonymMap(); //populate the map
boolean found = false;
Scanner in = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
String input = null;
System.out.println("Welcome To Artifical Intelligence DataBase ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
}

Your synonymMap should be organised other way arround, the key are the "synonyms" and the value is their common output.
So in your example:
String word = "bank";
String synonymn[] = { "safe", "treasury", "credit union" };
for (String syn : synonymn)
synonymMap.put(syn, word);
Then when user enters a word you check if it exists in the synonymMap and if so you return its value:
String syn = synonynMap.get(input);
if (syn != null) return syn;
else return input;

you can add every word of your synonym[] as key to your map too. of course with an array of synonyms containing the word and all other synonyms. i know there have to be better approaches, but thats the easiest way i can think of at the moment

Related

Processing the particular key value pair in set of key value pairs in java

The string can be
"accountno=18&username=abc&password=1236" or "username=abc&accountno=18&password=1236" or the accountno can be present anywhere in the string.
I need to get the accountno details from this string using a key value pair. I used spilt on "&" but I'm unable to get the result.
import java.util.regex.*;
public class RegexStrings {
public static void main(String[] args) {
String input = "accountno=18&username=abc&password=1236";
String exten = null;
Matcher m = Pattern.compile("^accountno: (.&?)$", Pattern.MULTILINE).matcher(input);
if (m.find()) {
exten = m.group(1);
}
System.out.println("AccountNo: "+exten);
}
}
How can I get the accountno value from this above string as key value pair in java
You may handle this by first splitting on & to isolate each key/value pair, then iterate that collection and populate a map:
String input = "accountno=18&username=abc&password=1236";
String[] parts = input.split("&");
Map<String, String> map = new HashMap<>();
for (String part : parts) {
map.put(part.split("=")[0], part.split("=")[1]);
}
System.out.println("account number is: " + map.get("accountno"));
This prints:
account number is: 18
Using some simple tools, like string.split and Map, you can easly do that:
Map<String, String> parse(String frase){
Map<String, String> map = new TreeMap<>();
String words[] = frase.aplit("\\&");
for(String word : words){
String keyValuePair = word.split("\\=");
String key = keyValuePair[0];
String value = keyValuePair[1];
map.put(key, value);
}
return map;
}
To get a specific value, like "accountno", just retrive that key map.get("accountno")
The same answer mentioned by #vinicius can be achieved using Java 8 by :
Map<String, String> map = Arrays.stream(input.split("&"))
.map(str -> str.split("="))
.collect(Collectors.toMap(s -> s[0],s -> s[1]));
//To retrieve accountno from map
System.out.println(map.get("accountno"));
As you said
the accountno can be present anywhere in the string
String input = "accountno=18&username=abc&password=1236";
//input = "username=abc&accountno=19&password=1236";
Matcher m = Pattern.compile("&?accountno\\s*=\\s*(\\w+)&?").matcher(input);
if (m.find()) {
System.out.println("Account no " + m.group(1));
}
This would work even when accountno is somewhere in the middle of the string
Output:
Account no 18
You can try out regex here:
https://regex101.com/r/nOHmzc/2

How to get values from the second column of a 2d array based on the fiest column value?

I have a Set of data. For example:
car accord
car civic
suv landcruzer
suv landrover
muv innova
I want store it in a scanner or hash map and retrieve the values based on the input.
If "car" is the input I want to pass URL+/accord and URL+/civic as its output
If "muv" is the input, I want to pass URL+/innova as its output
String URL = "www.abc.com";
String Vehicletype = "";
#DataProvider(name = "irLanguage")
public Object[][] lang() {
#SuppressWarnings("resource")
Scanner s = new Scanner(
"Car /accord/\n" +
"Car /civic/\n" +
"suv /landcruzer/\n" +
"suv /rangerover/\n" +
"muv /innova/\n");
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
while (s.hasNext()) {
String key = s.next();
if (!map.containsKey(key))
map.put(key, new LinkedList<String>());
map.get(key).add(s.next());
}
urlArray = map.get(vehicletype);
String[][] shades = new String[urlArray.size()][2];
for (int i = 0; i < urlArray.size(); i++) {
shades[i][0] = urlArray.get(i).toString();
shades[i][1] = URL + urlArray.get(i).toString();
lang = shades[i][0];
System.out.println(shades[i][0]);
}
return shades;
}
Here, the code is working fine. That is , if the input vehicle type is car then the output url is www.abc.com/accord/ and www.abc.com/civic/
and if the vehicle type is muv, it only returns www.abc.com/innova/ . This setup works fine for me. But, I wonder if there is any simpler method to do this.
Can anybody with good knowledge in java can help?
You have the right idea, I would build a HashMap that contains one Key (e.g. "car") and all the desired Values for that Key (e.g. "accord", "civic")
HashMap<String, ArrayList<String>> vehicles = new HashMap<String, ArrayList<String>>();
ArrayList<String> makes = new ArrayList<String>();
makes.add("accord");
makes.add("civic");
vehicles.put("car", makes);
makes.clear();
makes.add("landcruzer");
makes.add("rangerover");
vehicles.put("suv", makes);
makes.clear();
makes.add("innova");
vehicles.put("muv", makes);
makes.clear();
Now that you've got the vehicles HashMap built, you can fetch a Key and get all Values and build your URLs.
makes = vehicles.get("car");
for (String make : makes)
{
System.out.println("www.abc.com/" + make);
}

In Java, how do you loop through a string and check if it contains the keys in a hash map?

The goal is to write a text message abbreviation expander program that takes a string and checks for common abbreviations like LOL, IDK, etc. and replace them with the full length sentence, laugh out loud, I don't know, etc.
import java.util.HashMap;
import java.util.Scanner;
public class TextMsgExpander {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter text: ");
String userInput = scnr.nextLine();
System.out.println("You entered: " + userInput);
// Create new instance of Hash Map
HashMap<String, String> map = new HashMap<String, String>();
//Key value pairs
map.put("LOL", "laugh out loud");
map.put("IDK", "I don't know");
map.put("BFF", "best friend forever");
map.put("TTYL", "talk to you later");
map.put("JK", "just kidding");
map.put("TMI", "too much information");
map.put("IMHO", "in my humble opinion");
//Access points
String LOL = map.get("LOL");
String IDK = map.get("IDK");
String BFF = map.get("BFF");
String TTYL = map.get("TTYL");
String JK = map.get("JK");
String TMI = map.get("TMI");
String IMHO = map.get("IMHO");
System.out.println(TMI);
// While user input contains any of the keys, replace keys with
// values.
return;
}
}
You can instead iterate(loop) over the complete set of keys and look for them in the userInput, if they are present replace them with the respective value from the map as :
for (Map.Entry<String, String> entry : map.entrySet()) {
if (userInput.contains(entry.getKey())) {
userInput = userInput.replaceAll(entry.getKey(), entry.getValue());
}
}
System.out.println("Converted string - " + userInput);

Adding multiple values to one key in a HashMap

I am working on a project where I will be given two files; one with jumbled up words and the other with real words. I then need to print out the list of jumbled up words in alphabetical order with its matching real word(s) next to it. The catch is that there can be multiple real words per jumbled up word.
For example:
cta cat
ezrba zebra
psot post stop
I completed the program without accounting for the multiple words per jumbled up words, so in my HashMap I had to change < String , String > to < String , List < String > >, but after doing this I ran into some errors in the .get and .put methods. How can I get multiple words stored per key for each jumbled up word? Thank you for your help.
My code is below:
import java.io.*;
import java.util.*;
public class Project5
{
public static void main (String[] args) throws Exception
{
BufferedReader dictionaryList = new BufferedReader( new FileReader( args[0] ) );
BufferedReader scrambleList = new BufferedReader( new FileReader( args[1] ) );
HashMap<String, List<String>> dWordMap = new HashMap<String, List<String>>();
ArrayList<String> scrambled = new ArrayList<String>();
while (dictionaryList.ready())
{
String word = dictionaryList.readLine();
//throw in an if statement to account for multiple words
dWordMap.put(createKey(word), word);
}
dictionaryList.close();
ArrayList<String> scrambledList = new ArrayList<String>();
while (scrambleList.ready())
{
String scrambledWord = scrambleList.readLine();
scrambledList.add(scrambledWord);
}
scrambleList.close();
Collections.sort(scrambledList);
for (String words : scrambledList)
{
String dictionaryWord = dWordMap.get(createKey(words));
System.out.println(words + " " + dictionaryWord);
}
}
private static String createKey(String word)
{
char[] characterWord = word.toCharArray();
Arrays.sort(characterWord);
return new String(characterWord);
}
}
you could do something like :
replace the line:
dWordMap.put(createKey(word), word);
with:
String key = createKey(word);
List<String> scrambled = dWordMap.get(key);
//make sure that scrambled words list is initialized in the map for the sorted key.
if(scrambled == null){
scrambled = new ArrayList<String>();
dWordMap.put(key, scrambled);
}
//add the word to the list
scrambled.add(word);
dWordMap.put(createKey(word), word);
The dwordMap is of type HashMap>. So instead of word i.e. String it should be List.

How to combine scanner and multimap?

I have two files and am trying to read each file line by line by using scanner. Also, I would like to combine these two file with the same Key(name) by using multimap in order to combine these two file into one. Here is the script I have so far. Can someone please give me the suggestion? Thank you.
001.csv contains:
David 188 Male doctor A
Jacob 190 Male CEO A+
Sam 175 Male Engineer A-
002.txt contains:
David 80kg US3000
Jacob 70kg US100000
Sam 65kg US80000
Source code:
public class same_test{
public static void main (String[] args) throws FileNotFoundException {
MultiMap multiMap = new MultiValueMap();
Scanner scanner1 = new Scanner(new File("001.csv"));
Scanner scanner2 = new Scanner(new File("002.txt"));
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\t",2);
String TheName = array[0];
String score = array[1];
multiMap.put(TheName,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\t",2);
String TheName2 = array2[0];
String rs = array2[1];
multiMap.put(TheName2,rs);
}
Set<String> keys = multiMap.keyset();
for (String key : keys){
System.out.println(key + "\t" + multiMap.get(key) );
}
}
}
Plz share what problem you facing or output you getting.
I run you code, it works for me.
I used MultiHashMap.
public static void main (String[] args) throws FileNotFoundException {
MultiMap multiMap = new MultiHashMap();
Scanner scanner1 = new Scanner(new File("/obp/f1.csv"));
Scanner scanner2 = new Scanner(new File("/obp/f2.csv"));
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\\s",2);
String TheName = array[0];
String score = array[1];
multiMap.put(TheName,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\\s",2);
String TheName2 = array2[0];
String rs = array2[1];
multiMap.put(TheName2,rs);
}
Set<String> keys = multiMap.keySet();
for (String key : keys){
System.out.println(key + "\t" + multiMap.get(key) );
}
}
output
David [188 Male doctor A , 80kg US3000 ]
Jacob [190 Male CEO A+ , 70kg US100000 ]
Sam [ 175 Male Engineer A- , 65kg US80000 ]
This answer is limited to the constraint that there is always a unique name like David. i.e. there will be only one David in the both the files.
Use
HashMap<String,Person> personMap = new HashMap<String,Person>();
Person Class will look like
class Person {
String name;
String sex;
int height;
int weight;
}
Note : Mark fields as private along with public setters and getters
Where Person is your POJO class containing all the relevant fields for a person. You will create a new Java POJO instance for every name during the scan of the first file and put an entry of this object mapped with the name. then, in the second scanner loop, you can get the Person object out of the map with the name from the second file (which matches actually) and set the remaining fields in it. On completion of the method, you will get all the details in the form of Person instances mapped with their names

Categories