Let's say we have a string: string text = "Hello my name is $$name; and my surname is $$surname;"
It references 2 variables, identified by double dollar sign: name and surname
We also have a hashmap:
HashMap<String, String> variables = new HashMap<String, String>();
variables.put("name", "John");
variables.put("surname", "Doe");
How do I replace/interpolate variables in a string with their matched Regex values as hashmap keys? (perhaps there's no need to use Regex and Java has this implementation)
In the end, I want variable string text to equal "Hello my name is John and my surname is Doe"
EDIT: What I meant is replacing the key/variable with the hashmap value without knowing the key. For example, we have a string and we must replace all $$variable; values inside in with the map[variable].
What would be the fastest way of replacing this string?
You would have to use some regex, parse the input and lookup every key in the Map, like that:
import java.util.Map;
import java.util.regex.Pattern;
public class T2 {
/** Pattern for the variables syntax */
public static final Pattern PATTERN = Pattern.compile("\\$\\$([a-zA-Z]+);");
public static void main(String[] args) {
String s = "Hello my name is $$name; and my surname is $$surname;";
Map<String, String> variables = Map.of("name", "John", "surname", "Doe");
String ret = replaceVariables(s, variables);
System.out.println(ret);
}
private static String replaceVariables(final CharSequence s, final Map<? super String, String> variables) {
return PATTERN.matcher(s).replaceAll(mr -> variables.getOrDefault(mr.group(1), ""));
}
}
Output:
Hello my name is John and my surname is Doe
You can iterate over variables and replace the matched keys with the corresponding values without knowing the key using a foreach loop.
for(Map.Entry<String, String> e: variables.entrySet()) {
text = text.replace("$$"+e.getKey(), e.getValue());
}
Try this:
String text = "Hello my name is $$name; and my surname is $$surname;";
Map<String, String> variables = new HashMap<>();
variables.put("name", "John");
variables.put("surname", "Doe");
for(Map.Entry<String, String> e: variables.entrySet()) {
text = text.replace("$$"+e.getKey(), e.getValue());
}
System.out.println(text);
Output:
Hello my name is John; and my surname is Doe;
Related
I have a Treemap:
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
It counts words that are put in, for example if I insert:
"Hi hello hi"
It prints:
{Hi=2, Hello=1}
I want to replace that "," with a "\n", but I did not understand the methods in Java library. Is this possible to do? And is it possible to convert the whole TreeMap to a String?
When printing the map to the System.out is uses the map's toString function to print the map to the console.
You could either string replace the comma with a newline like this:
String stringRepresentation = map.toString().replace(", ", "\n");
This might however poses problems when your key in the map contains commas.
Or you could create a function to produce the desired string format:
public String mapToMyString(Map<String, Integer> map) {
StringBuilder builder = new StringBuilder("{");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
builder.append(entry.getKey()).append('=').append(entry.getValue()).append('\n');
}
builder.append('}');
return builder.toString();
}
String stringRepresentation = mapToMyString(map);
Guava has a lot of useful methods. Look at Joiner.MapJoiner
Joiner.MapJoiner joiner = Joiner.on('\n').withKeyValueSeparator("=");
System.out.println(joiner.join(map));
String input data is
{phone=333-333-3333, pr_specialist_email=null, sic_code=2391, status=ACTIVE, address1=E.BALL Drive, fax=333-888-3315, naics_code=325220, client_id=862222, bus_name=ENTERPRISES, address2=null, contact=BYRON BUEGE}
Key and values will increase in the array.
I want to get the value for each key ie myString.get("phone") should return 333-333-3333
I am using Java 1.7, is there any tools I can use this to parse the data and get the values.
Some of my input is having values like,
{phone=000000002,Desc="Light PROPERTITES, LCC", Address1="C/O ABC RICHARD",Address2="6508 THOUSAND OAKS BLVD.,",Adress3="SUITE 1120",city=MEMPHIS,state=TN,name=,dob=,DNE=,}
Comma separator doesn't work here
Here is a simple function that will do exacly what you want. It takes your string as an input and returns a Hashmap containing all the keys and values.
private HashMap<String, String> getKeyValueMap(String str) {
// Trim the curly ({}) brackets
str = str.trim().substring(1, str.length() - 1);
// Split all the key-values tuples
String[] split = str.split(",");
String[] keyValue;
HashMap<String, String> map = new HashMap<String, String>();
for (String tuple : split) {
// Seperate the key from the value and put them in the HashMap
keyValue = tuple.split("=");
map.put(keyValue[0].trim(), keyValue[1].trim());
}
// Return the HashMap with all the key-value combinations
return map;
}
Note: This will not work if there's ever a '=' or ',' character in any of the key names or values.
To get any value, all you have to do is:
HashMap<String, String> map = getKeyValueMap(...);
String value = map.get(key);
You can write a simple parser yourself. I'll exclude error checking in this code for brevity.
You should first remove the { and } characters, then split by ', ' and split each resulting string by =. At last add the results into a map.
String input = ...;
Map<String, String> map = new HashMap<>();
input = input.substring(1, input.length() - 1);
String elements[] = input.split(", ");
for(String elem : elements)
{
String values[] = elem.split("=");
map.put(values[0].trim(), values[1].trim());
}
Then, to retrieve a value, just do
String value = map.get("YOURKEY");
You can use "Google Core Libraries for Java API" MapSplitter to do your job.
First remove the curly braces using substring method and use the below code to do your job.
Map<String, String> splitKeyValues = Splitter.on(",")
.omitEmptyStrings()
.trimResults()
.withKeyValueSeparator("=")
.split(stringToSplit);
I need to split a sentence into two strings, the first string store as key and the second string store as value in HashMap.
For example:
String sent="4562=This is example";
This is my sentence, I split into two strings using the following line:
sent.split("=");
I want to store the first string (4562) as key, and the second string store as value in HashMap.
Can you please share your ideas or solution for problem?
You are stating your own answer:
HashMap<String, String> map = new HashMap<String, String>(); //initialize the hashmap
String s = "4562=This is example"; //initialize your string
String[] parts = s.split("="); //split it on the =
map.put(parts[0], parts[1]); //put it in the map as key, value
You can store in a hashmap like this:
String sent = "4562=This is example";
String[] split = sent.split("=");
HashMap<Integer, String> keysValues = new HashMap<Integer, String>();
keysValues.put(Integer.parseInt(split[0]), split[1]);
You can store Integer as key and String as value...or String, String either way will work depends on what you want.
the method split returns a String Array so store the result into an String array and call the hashmap.put(key,value) method
like this
String[] a = split.("=");
hasmap.put(a[0],a[1]);
note if you have several = in the string you will loose some of it in the value of the hashmap!
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<String, String>();
String s = "4562=This is example";
String[] parts = s.split("=");
if (parts.length == 2) {
myMap.put(parts[0], parts[1]);
}
System.out.println(myMap);
}
Output
{4562=This is example}
enter code here
I used Scanner to read through A.txt to generate A Hashmap,
also same method to read through B.txt to have B Hashmap.
These two hashmap have the "SOME" same key and would like to combine with each other.
If the key is are the same, print out "key, value1, value2".
Here is I have so far :
public static void main (String[] args) throws FileNotFoundException {
Scanner scanner1 = new Scanner(new File("score.txt"));
Map<String, String> tolerance = new HashMap<>();
Scanner scanner2 = new Scanner(new File("Count2.txt"));
Map<String, String> Pdegree = new HashMap<>();
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\t",2);
String Name = array[0];
String score = array[1];
tolerance.put(Name,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\t",2);
String Name2 = array2[0];
String degree = array2[1];
Pdegree.put(Name2,degree);
}
for(Map.Entry<String, String> entry : tolerance.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
for(Map.Entry<String, String> entry2 : Pdegree.entrySet()) {
String key2 = entry2.getKey();
String value2 = entry2.getValue();
if(key==key2){
System.out.println(key2 + "\t" + value + "\t" + value2);
}
}
}
}
}
Neither results nor error messages would show.
My question is how to extract the same key with respective values from two maps. Thanks.
I found the answer by myself. It should be
if(key.equals(key2))
You may use map1.putAll(map2) to combine two maps;
Why not use Guava's multimap? I believe that if you use put all and it comes across two identical keys, it simply adds a second value to the key. Then you can print out all teh key value pairs. If it has identical key and identical value what it does is implementation dependent.
https://guava-libraries.googlecode.com/svn/tags/release03/javadoc/com/google/common/collect/Multimap.html#put(K, V)
I have a HashMap with String as key and List as value.
Name of the HashMap is pageMap.
Say this pageMap has the following key and value:
key = order
value = [page1, page2, page3]
now I want to display in the following pattern:
order
page1
page2
page3
key2
value1
value2
value3
value4
Please tell me how do I do that?
import java.util.*;
import java.lang.*;
public class StringListMapExample {
public static String asTreeFormattedString(HashMap<String,List<String>> map) {
final StringBuilder builder = new StringBuilder();
for (String key : map.keySet()) {
builder.append(key + "\n");
for (String string : map.get(key)) {
builder.append("\t" + string + "\n");
}
}
return builder.toString();
}
public static void main(String[] args) {
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
map.put("order", Arrays.asList(new String[]{"page1", "page2", "page3"}));
System.out.println(asTreeFormattedString(map));
}
}
Actually the solution is quite straightforward.
hashmap.get(key).iterator();
is an iterator for the list of the given key.
Why did you not try to figure it out yourself?
Iterate using iterator through all keys of hashmap using keyset()
{
print key
Iterate through value list using iterator
{
print each value
}
}
public String formatDictionary(Map<String, List<String>> map){
String output = '';
for (String key : map.keySet()){
output = output + key + "\n";
for (String value: map.get(s)){
output = output + "\t" + value + "\n";
return output
Which is pretty similar to Jeppi's answer, but using string concatenation which is one of my favorite things about Java. I haven't run any benchmarks, but my guess is that his would be a little faster, but mine would have less overhead.