for (Entry<String, String> entry : map.entrySet()) {
String delimiter = "**";
result = result.replace(delimiter + entry.getKey() + delimiter, entry.getValue());
}
result is my string to be replaced by hashmap values.
Here string (result variable) is returning as itself not replacing any value.
Please any one have suggestions ?
From comment
My hashmap contains,
HashMap<String, String> map = new HashMap<String, String>();
map.put("Rid", serviceBooking.getId().toString());
map.put("Rname", customer.getName());
map.put("Rnic", "");
The algorithm OK Here's a working, executable example:
// sample input
String input = "abcd **Rid** efgh";
// a small map
Map<String, String> map = new HashMap<String, String>();
map.put("Rid","VALUE");
// the loop that replaces the **Rid** substring
for (Map.Entry<String,String> entry:map.entrySet()){
input = input.replace("**"+entry.getKey()+"**", entry.getValue());
System.out.println(input);
}
It prints
abcd VALUE efgh
Either your HashMap is empty, or the original string doesn't contain anything corresponding to the keys in the map, or you wrote two asterisks where you meant one, or you didn't escape it/them when you needed to, or ...
Impossible to improve on that without seeing the original string and the contents of the map.
Related
I have a map as Map<String,String>
and the entries are like map.put("c_09.01--x28", "OTH"). In this I use split the key and use the x28 to change it to OTH. So my question is whether I should use split operation or use map within a map and map.put("c_09.01", newMap) where newMap will have map.put("x28", 'OTH'). Which one will give me better performance? sample code where I have used that is
for (Entry<String,String> sheetEntry : this.getSheetCD().getUserDefinedSheetCodeMap().entrySet()) {
String Key = sheet.getKey().split("--")[1];
int sheetIndex = template.getSheetIndex(sheetKey);
if(sheetEntry.getKey().toUpperCase().startsWith(getFileName()){
String newSheetName = sheetEntry.getValue();
template.setSheetName(sheetIndex, newSheetName);
}
}
Please let me know if more information is needed. Regards.
You should use Split operation because if you are using split operation so at the time of iteration the object from map that time you can iterate the value using single forEach loop.
Sample Code
String str[] = "c_09.01--x28".split("--")[1];
Map<String, String> map = new HashMap<>();
map.put(str, "OTH");
for(Map.Entry eMap:map.entrySet()){ //single forEach loop
System.out.println("Key : "+eMap.getKey());
System.out.println("Value : "+eMap.getValue());
}
Output
Key : x28
Value : OTH
If you use map.put("c_09.01", newMap); this one, so you need to iterate two times. Like first you need to iterate newMap using key c_09.01 than again you need to iterate OTH using key x28.
Sample Code
String str[] = "c_09.01--x28".split("--");
Map<String, String> map = new HashMap<>();
map.put(str[1], "OTH");
Map<String, Map> map1 = new HashMap<>();
map1.put(str[0], map);
for(Map.Entry eMap : map1.entrySet()){ //First forEach Loop
System.out.println("Key : "+eMap.getKey()); //getiing key "c_09.01"
Map<String, String> map2 = (Map<String, String>) eMap.getValue(); //getting map and need to be cast because it return object type
for(Map.Entry eMap1 : map2.entrySet()){ // Second forEach loop
System.out.println("Key Using map.put(String, newMAp) : "+eMap1.getKey());
System.out.println("ValueUsing map.put(String, newMAp) : "+eMap1.getValue());
}
}
Output
Key : c_09.01
Key Using map.put(String, newMAp) : x28
ValueUsing map.put(String, newMAp) : OTH
So i guess you should use split operation.
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 have an homework to do, so I have finished the script but the problem is with the values.
The main code is (I cannot change it due to homework) :
List<String> result = cw.getResult();
for (String wordRes : result) {
System.out.println(wordRes);
}
It have to return:
abc 2
def 2
ghi 1
I have no idea how to handle that.
Now only shows:
abc
def
ghi
I have no idea how to change this method getResult to return with the value of the hashmap as well without changing the first main code.
public List<String> getResult() {
List<String> keyList = new ArrayList<String>(list.keySet());
return keyList;
}
The hashmap is: {abc=2, def=2, ghi=1}
And list: Map<String, Integer> list = new HashMap<String, Integer>();
Please help me if you know any resolution.
I think that now that you have learned about keySet and valueSet, your next task is to learn about entrySet. That's a collection of Map.Entry<K,V> items, which are in turn composed of the key and the value.
That's precisely what you need to complete your task - simply iterate over the entrySet of your Map while adding a concatenation of the value and the key to your result list:
result.add(entry.getKey() + " " + entry.getValue());
Note that if you use a regular HashMap, the items in the result would not be arranged in any particular order.
You need to change this line:
List<String> keyList = new ArrayList<String>(list.keySet());
to:
//first create the new List
List<String> keyList = new List<String>();
//iterate through the map and insert the key + ' ' + value as text
foreach(string item in list.keySet())
{
keyList.add(item+' '+list[item]);
}
return keyList;
I haven't written java in a while so compiler errors might appear, but the idea should work
Well simplest way make an ArrayList and add as #dasblinkenlight said...
Iterator<?> it = list.entrySet().iterator();
while (it.hasNext()) {
#SuppressWarnings("rawtypes")
Map.Entry maps = (Map.Entry) it.next();
lista.add(maps.getKey() + " " + maps.getValue());
}
}
public List<String> getResult() {
List<String> temp = lista;
return temp;
}
If you want to iterate over map entries in order of keys, use an ordered map:
Map<String, Integer> map = new TreeMap<String, Integer>();
Then add your entries, and to print:
for (Map.Entry<String, Ibteger> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
I have following LinkedHashMap declaration.
LinkedHashMap<String, ArrayList<String>> test1
my point is how can i iterate through this hash map.
I want to do this following, for each key get the corresponding arraylist and print the values of the arraylist one by one against the key.
I tried this but get only returns string,
String key = iterator.next().toString();
ArrayList<String> value = (ArrayList<String> )test1.get(key)
for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// now work with key and value...
}
By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.
I'm assuming you have a typo in your get statement and that it should be test1.get(key). If so, I'm not sure why it is not returning an ArrayList unless you are not putting in the correct type in the map in the first place.
This should work:
// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());
// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
String key = entry.getKey();
List<String>value = entry.getValue();
// ...
}
or you can use
// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
List<String>value = test1.get(key);
// ...
}
You should use the interface names when declaring your vars (and in your generic params) unless you have a very specific reason why you are defining using the implementation.
In Java 8:
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});
You can use the entry set and iterate over the entries which allows you to access both, key and value, directly.
for (Entry<String, ArrayList<String>> entry : test1.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
I tried this but get only returns string
Why do you think so? The method get returns the type E for which the generic type parameter was chosen, in your case ArrayList<String>.
// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
// iterate over each entry
for(String item : entry.getValue()){
// print the map's key with each value in the ArrayList
System.out.println(entry.getKey() + ": " + item);
}
}