String compare with keys in Map in Java - 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

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;
}
}

Related

Splitting based on delimiter and string

String CompanyData = "{ChargeCompany1Cnt:0,ChargeCompany2Cnt:73,ChargeCompany3Cnt:44,BalanceCompany3Cnt:0,ChargeCompany4Flag:green,BalanceCompany2Flag:green,BalanceCompany1Cnt:0,ChargeCompany3Flag:red,ChargeCompany1Flag:green,BalanceCompany4Flag:green,BalanceCompany1Flag:green,BalanceCompany2Cnt:0,BalanceCompany4Cnt:0,BalanceCompany3Flag:green,ChargeCompany2Flag:red,ChargeCompany4Cnt:6}";
CompanyData is my string I am splitting the data like below. There is no issue with this code, but if the order is changed in the string splitting is breaking.
how to split this string and assign to another string by its name(like splitting based on ChargeCompany1Cnt, ChargeCompany2Cnt). i have used cut and sed commands in UNIX to do this, right now converting my Shell script into JAVA. So sorry if it's a basic question
String ChargeCompany1Cnt=CompanyData.split(,)[0].replace("{","");
String ChargeCompany2Cnt=CompanyData.split(,)[1];
String ChargeCompany3Cnt=CompanyData.split(,)[2];
String BalanceCompany3Cnt=CompanyData.split(,)[3];
String ChargeCompany1Flag=CompanyData.split(,)[8];
Basically I need to find String like ChargeCompany2Cnt,ChargeCompany1Flag in CompanyData and print ChargeCompany2Cnt:73 ChargeCompany1Flag:green
Please note if this is JSON object you can parse it easily with ObjectMapper
of Jacson. you can use the below code for manual parsing
String CompanyData = "{ChargeCompany1Cnt:0,ChargeCompany2Cnt:73,ChargeCompany3Cnt:44,BalanceCompany3Cnt:0,ChargeCompany4Flag:green,BalanceCompany2Flag:green,BalanceCompany1Cnt:0,ChargeCompany3Flag:red,ChargeCompany1Flag:green,BalanceCompany4Flag:green,BalanceCompany1Flag:green,BalanceCompany2Cnt:0,BalanceCompany4Cnt:0,BalanceCompany3Flag:green,ChargeCompany2Flag:red,ChargeCompany4Cnt:6}";
HashMap<String,String> mymap = new HashMap<String,String>();
for ( String s: CompanyData.split("[?,{}]")) {
if (!s.equals(""))
mymap.put(s.split(":")[0],s.split(":")[1]); }
for (HashMap.Entry<String, String> entry : mymap.entrySet()) {
String key = entry.getKey().toString();;
String value = entry.getValue();
System.out.println( key + " = " + value );
Your question isn't too clear, but perhaps this snippet will point you in the right direction:
List<String> companyCount = new ArrayList<>();
String[] companies = CompanyData.substring(1, -1).split(",");
for (String companyCnt : companies) {
companyCount.add(companyCnt);
}
Incidentally, you can probably perform this whole operation without use of cut(1) as well.
Depending on how you intend to use the variables you could alternatively create a set of key-value pairs instead of explicitly declaring each variable.
Then you could split the names out (i.e. split each element further on :) and use them as keys without needing to know which is which.

Changing LinkedHashMapValues

Below is data from 2 linkedHashMaps:
valueMap: { y=9.0, c=2.0, m=3.0, x=2.0}
formulaMap: { y=null, ==null, m=null, *=null, x=null, +=null, c=null, -=null, (=null, )=null, /=null}
What I want to do is input the the values from the first map into the corresponding positions in the second map. Both maps take String,Double as parameters.
Here is my attempt so far:
for(Map.Entry<String,Double> entryNumber: valueMap.entrySet()){
double doubleOfValueMap = entryNumber.getValue();
for(String StringFromValueMap: strArray){
for(Map.Entry<String,Double> entryFormula: formulaMap.entrySet()){
String StringFromFormulaMap = entryFormula.toString();
if(StringFromFormulaMap.contains(StringFromValueMap)){
entryFormula.setValue(doubleOfValueMap);
}
}
}
}
The problem with doing this is that it will set all of the values i.e. y,m,x,c to the value of the last double. Iterating through the values won't work either as the values are normally in a different order those in the formulaMap. Ideally what I need is to say is if the string in formulaMap is the same as the string in valueMap, set the value in formulaMap to the same value as in valueMap.
Let me know if you have any ideas as to what I can do?
This is quite simple:
formulaMap.putAll(valueMap);
If your value map contains key which are not contained in formulaMap, and you don't want to alter the original, do:
final Map<String, Double> map = new LinkedHashMap<String, Double>(valueMap);
map.keySet().retainAll(formulaMap.keySet());
formulaMap.putAll(map);
Edit due to comment It appears the problem was not at all what I thought, so here goes:
// The result map
for (final String key: formulaMap.keySet()) {
map.put(formulaMap.get(key), valueMap.get(key));
// Either return the new map, or do:
valueMap.clear();
valueMap.putAll(map);
for(Map.Entry<String,Double> valueFormula: valueMap.entrySet()){
formulaMap.put(valueFormula.getKey(), valueFormula.value());
}

Comparing java variables and printing

Suppose , I have some variables as :
String x="abcd";
String y="qwert";
String z="mnvji";
and more...
I take an input from user.
If user inputs 'x' , I print that string i.e. I print "abcd"
If user inputs 'y' , I print "qwert" and so on...
Is there any way to do it without switches or ifs??
Thank you,friends, in advance.
You could create a map from input string to result. Initialize the map:
Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
And when you want to print the result from the input from the user:
Scanner s = new Scanner(System.in);
while (s.hasNextLine())
System.out.println(map.get(s.nextLine()));
Local variable names aren't available at runtime and reading field knowing it's name requires some reflection (see #amit's answer). You need a map:
Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
Now just take value from that map:
String value = map.get(userInput);
value will be null if it doesn't match any of x/y/z.
As we can approach like that also,
String input[]=new String['z'];
input['X']="abcd";
input['Y']="qwert";
input['Z']="mnvji";
System.out.println(input['X']);
But it will come under some limitation
Map collection using key value pair implementation solve your problem .
put varible x,y,z as key and "abcd" ,.. as value.
Retrieve value from specific key according to input value.
Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
to get value
String value = map .get(inputValue).
Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
Scanner s = new Scanner(System.in);
while (s.hasNextLine())
System.out.println(map.get(s.nextLine()));
will probably work.
Put your variable set into a HashMap as (key,value) pairs and just retrieve the value for the particular key when user inputs the key.
create an string array in which x,y,z should be indexes and store the content relatively ...
get the user input and pass it to the array as index ..you will get it..
If you really don't want to use switches or ifs (and I'd assume you include maps in that) then you'd have to use reflection to get the names of all the variables and decide which to print on them. Here's the basics:
Class yourClass = Class.forName("yourpackagename.YourClassName")
Field[] allFields = yourClass.getDeclaredFields();
String[] fieldNames = new String[allFields.length];
for(int i = 0; i < fieldNames.length; i++)
{
fieldNames[i] = allFields [i].getName();
}
//Get name of field user wants to display, and look it up in
//the fieldNames array to get the index of it, store this index
Object instance = yourClass.newInstance();
System.out.println(allFields[indexToDisplay].get(instance));
Of course, this could well be overkill.
If you have no choice but using object variables (fields) and not a Map as suggested by other answers - you might want to use reflection, and specifically the Class.getField() and Class.getDeclaredField() methods-
Field f = MyClass.class.getDeclaredField("x");
System.out.println(f.get(myObject));
Where MyClass is your class name and myObject is the object you want the value from.
Note that with this approach - you cannot add fields - you can only get existing ones.

How to get the longest possible key in java to match a given String

I have written a code to check if a string has the key in a give Map and replace the key with the value in the string.
Below is the code
String s ="VamshiKrishnaA";
Map<String,String> h = new HashMap<String,String>();
h.put("Vamshi", "89");
h.put("VamshiKrishnaA","dataDir");
h.put("VamshiKrishna","dataDira");
h.put("VamshiK", "krihsn");
String key="";
Iterator<String> i =h.keySet().iterator();
while(i.hasNext()){
key=i.next();
if(s.contains(key)){
s=s.replace(key, h.get(key));
}
}
System.out.println(s);
When i run the above code, i got the output as dataDiraA but i need output to be dataDir.
I dont have control over the order of the key and values it is autogenerated.
Need any help in this regard
You need to track the length of the currently matched key, and only use the one which is the longest:
String matchedKey = null;
while (i.hasNext()) {
key = i.next();
if (s.contains(key) && (matchedKey == null || matchedKey.length() < key.length())) {
matchedKey = key;
}
}
if (matchedKey != null) {
s = s.replace(matchedKey, h.get(matchedKey));
}
You should call equals() instead of contains():
if(s.equals(key))
If there is some way to order your keys, for example, by length, you might have look at TreeMap, where all keys will be ordered using provided comparator.
On the other hand, if there are not much keys and you knows exact ordering you might just use LinkedHashMap. This way keys will be iterated in the order you have put them. Like this:
String s = "VamshiKrishnaA";
Map<String, String> h = new LinkedHashMap<String, String>();
h.put("VamshiKrishnaA", "dataDir");
h.put("VamshiKrishna", "dataDira");
h.put("VamshiK", "krihsn");
h.put("Vamshi", "89");
for (String key : h.keySet()) {
if (s.contains(key)) {
s = s.replace(key, h.get(key));
}
}
System.out.println(s);
contains() checks for a sub string , where as equals() checks for whole string , and other difference is , contains() takes object of CharSequence class where as equals() takes Object as its parameter !
Using equals() method ::
String s = "VamshiKrishnaA";
Map<String, String> h = new HashMap<String, String>();
h.put("Vamshi", "89");
h.put("VamshiKrishnaA", "dataDir");
h.put("VamshiKrishna", "dataDira");
h.put("VamshiK", "krihsn");
String key = "";
Iterator<String> i = h.keySet().iterator();
while (i.hasNext()) {
key = i.next();
if (s.equals(key)) {
//s = s.replace(key, h.get(key));
System.out.println(h.get(key));
}
}

How to convert String representation of ArrayList to ArrayList

I have an ArrayList, Whom i convert to String like
ArrayList str = (ArrayList) retrieveList.get(1);
...
makeCookie("userCredentialsCookie", str.toString(), httpServletResponce);
....
private void makeCookie(String name, String value, HttpServletResponse response) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);
} //end of makeCookie()
Now when i retrieve cookie value, i get String, but i again want to convert it into ArrayList like
private void addCookieValueToSession(HttpSession session, Cookie cookie, String attributeName) {
if (attributeName.equalsIgnoreCase("getusercredentials")) {
String value = cookie.getValue();
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
return;
}
String value = cookie.getValue();
session.setAttribute(attributeName, value);
} //end of addCookieValueToSession
How can i again convert it to ArrayList?
Thank you.
someList.toString() is not a proper way of serializing your data and will get you into trouble.
Since you need to store it as a String in a cookie, use JSON or XML. google-gson might be a good lib for you:
ArrayList str = (ArrayList) retrieveList.get(1);
String content = new Gson().toJson(str);
makeCookie("userCredentialsCookie", content, httpServletResponce);
//...
ArrayList userCredntialsList = new Gson().fromJson(cookie.getValue(), ArrayList.class);
As long as it's an ArrayList of String objects you should be able to write a small method which can parse the single String to re-create the list. The toString of an ArrayList will look something like this:
"[foo, bar, baz]"
So if that String is in the variable value, you could do something like this:
String debracketed = value.replace("[", "").replace("]", ""); // now be "foo, bar, baz"
String trimmed = debracketed.replaceAll("\\s+", ""); // now is "foo,bar,baz"
ArrayList<String> list = new ArrayList<String>(Arrays.asList(trimmed.split(","))); // now have an ArrayList containing "foo", "bar" and "baz"
Note, this is untested code.
Also, if it is not the case that your original ArrayList is a list of Strings, and is instead say, an ArrayList<MyDomainObject>, this approach will not work. For that your should instead find how to serialise/deserialise your objects correctly - toString is generally not a valid approach for this. It would be worth updating the question if that is the case.
You can't directly cast a String to ArrayList instead you need to create an ArrayList object to hold String values.
You need to change part of your code below:
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
to:
ArrayList<String> userCredentialsList = ( ArrayList<Strnig> ) session.getAttribute( attributeName );
if ( userCredentialsList == null ) {
userCredentialsList = new ArrayList<String>( 10 );
session.setAttribute(attributeName, userCredentialsList);
}
userCredentialsList.add( value );

Categories

Resources