I have a map whcih has the key value as long and value as String. The values of the map are obtained from the db and it is in the below format.
1: BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3,BusinessPartner.name4
2: BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3
6: ADDRESS.addressline1,ADDRESS.addressline2,ADDRESS.addressline3
where 1,2,6 are the keys.
I need to tokenize the strings that is for the key 1 the result should be
Businesspartner and the other values should be name1,name2,name3,name4.
I am doing this because i need to put these values into an another map as
Map(name1,name2,name3,name4)>
I can split the string but how to take Businesspartner as a common value for the other entities
Can anybody tell me how to do this
Thanks
would this work for your riquierment ?
public class Tokenize {
static Long keysFromDB[] = {1L, 2L, 6L};
static String stringsFromDB[] = {
"BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3,BusinessPartner.name4",
"BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3",
"ADDRESS.addressline1,ADDRESS.addressline2,ADDRESS.addressline3"};
#Test
public void tokenize() {
// use linked hashmap to preserve the order
Map<Long, Set<String>> tokenized = new LinkedHashMap<Long, Set<String>>();
int c = 0;
for(Long key : keysFromDB) {
// use linked hashset to preserve the order
Set<String> record = new LinkedHashSet<String>();
String splitedDBStrings[] = stringsFromDB[c++].split("\\.|,");
System.out.println("List: " + Arrays.asList(splitedDBStrings));
for(String s : splitedDBStrings) {
record.add(s);
}
System.out.println("Set: " + record);
tokenized.put(key, record);
}
System.out.println(tokenized);
}
}
run this
public static void main(String[] args){
Map<Long, String> dbmap = new HashMap<Long, String>();
dbmap.put((long) 1, "BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3,BusinessPartner.name4");
dbmap.put((long) 2, "BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3");
dbmap.put((long) 6, "ADDRESS.addressline1,ADDRESS.addressline2,ADDRESS.addressline3");
//Loop through the Map
Iterator<Entry<Long, String>> iterator = dbmap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Long, String> entry = (Map.Entry<Long, String>) iterator.next();
//Split the string on comma ','
//result entries should be 'BusinessPartner.name1', 'BusinessPartner.name2' etc
String[] commaSplit = entry.getValue().split(",");
//loop through each entry
for(int x=0; x<commaSplit.length; x++){
//Split on Full Stop
//Result should be 'BusinessPartner', 'name2'
String[] dotSplit = commaSplit[x].split("\\.");
//print out common Value
System.out.println("Common Value is : " + dotSplit[0]);
//print out second value
System.out.println("Second Value is : " + dotSplit[1]);
System.out.println();
}
}
}
output is something like this
Common Value is : BusinessPartner
Second Value is : name1
Common Value is : BusinessPartner
Second Value is : name2
Common Value is : BusinessPartner
Second Value is : name3
Common Value is : BusinessPartner
Second Value is : name4
Common Value is : BusinessPartner
Second Value is : name1
Common Value is : BusinessPartner
Second Value is : name2
Common Value is : BusinessPartner
Second Value is : name3
Common Value is : ADDRESS
Second Value is : addressline1
Common Value is : ADDRESS
Second Value is : addressline2
Common Value is : ADDRESS
Second Value is : addressline3
Lets start from the beginning:
final Pattern pattern = Pattern.compile("[,\\s*]?([^.]+)\\.([^,]+)[,\\s*]?");
final Map<Long, String> myMap = getMapFromSomewhere();
for(final Map.Entry<Long, String> entry : myMap.entrySet()) {
final String myString = entry.getValue();
final Matcher matcher = pattern.matcher(myString);
final Map<String, List<String>> tokenised = new HashMap<String, List<String>>();
while (matcher.find()) {
final String key = matcher.group(1);
List<String> names = tokenised.get(key);
if(names == null) {
names = new LinkedList<String>();
tokenised.put(key, names)
}
names.add(matcher.group(2));
}
//do stuff with map.
}
The regex breaks down as follows:
[,\\s*]? optionally matches a comma followed by whitespace of unknown (or zero) length
([^.]+)\\. matches everything up to the next stop followed by a "."
([^,]+) takes everything upto the next comma in a match group
[,\\s*]? optionally matches a comma followed by whitespace of unknown (or zero) length
Test case:
public static void main(String[] args) {
final Pattern pattern = Pattern.compile("[,\\s*]?([^.]+)\\.([^,]+)[,\\s*]?");
final String myString = "BusinessPartner.name1,BusinessPartner.name2,BusinessPartner.name3,BusinessPartner.name4";
final Matcher matcher = pattern.matcher(myString);
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
Output:
BusinessPartner
name1
BusinessPartner
name2
BusinessPartner
name3
BusinessPartner
name4
Related
I have this mathematical expression:
String exp = "k+(mP/P+mL/L)";
Then i create a new HashMap and put exactly the same params as the above expression :
Map<String, Integer> mp = new HashMap<>();
mp.put("k", 1);
mp.put("mP", 2);
mp.put("P", 3);
mp.put("mL", 4);
mp.put("L", 5);
Finally i continue doing a litteration all of the entry-set by replace the parameter of my expression to values and after that i print my result:
for(Map.Entry<String,Integer> e: mp.entrySet()){
exp = exp.replace(e.getKey(),e.getValue().toString());
}
System.out.println(exp);
the result of the above is : "1+(m3/3 +m5/5)"
*but i want this instead : "1+(2/3+4/5)"
Is there any way?
Use regular expression replaceAll with word-boundary \b.
exp = exp.replaceAll("\\b" + e.getKey() + "\\b", e.getValue().toString());
You could also look into the scripting API or the java REPL.
The problem is caused by HashMap not keeping insert order. Using LinkedHashMap, which keeps insertion order will solve the problem.
Map<String, Integer> mp = new LinkedHashMap<>();
String.replace() replaces all occurrence of the substring, so if P gets replaced before mP, it can lead to problems like the one you described. To avoid that, you can build the expression with placeholders, which don't have common letters. Like this for example:
String exp = "a+(b/c+d/e)";
You can also sort the keys by their length:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public static void main(String[] args) {
String exp = "k+(mP/P+mL/L)";
Map<String, Integer> mp = new HashMap<String, Integer>();
mp.put("mP", 2);
mp.put("mL", 4);
mp.put("k", 1);
mp.put("P", 3);
mp.put("L", 5);
String[] keys = new String[mp.keySet().size()];
int i = 0;
for (String k : mp.keySet()) {
keys[i] = k;
i++;
}
/* Sort array by string length (longest string at the beginning) */
Arrays.sort(keys, (a, b) -> Integer.compare(b.length(), a.length()));
for (String k : keys) {
exp = exp.replace(k, mp.get(k).toString());
}
System.out.println(exp); // 1+(2/3+4/5)
}
Can I pass a key of a value into variable in hashmap?
For example I have a key 987456321 for value "A". How to pass the key in a variable so that I can further subdivide the key and print it as 987-654-321,
by taking 987 as first,
654 as middle,
321 as last
So that I can print
first+ "-" + middle+ "-" + last as 987-654-321
by using toString() method.
I am new to Java, So help me Please
public static void main(String[] args)
{
HashMap<Long, String> hashMap = new HashMap<>();
hashMap.put(987456321L, "A");
hashMap.put(321654998L, "B");
hashMap.put(874563210L, "C");
hashMap.put(987453216L, "B");
hashMap.put(321650123L, "C");
hashMap.put(874568745L, "C");
System.out.println("Size of Map:"+hashMap.size());
System.out.println("Enter no: ");
userInput = new Scanner(System.in);
no = userInput.nextLong();
String name = hashMap.get(no);
System.out.println(name);
for (Map.Entry<Long, String> entry : hashMap.entrySet())
{
String key = entry.getKey().toString();
String value = entry.getValue();
System.out.println("name " + value + "- Number " + key);
}
}
You can iterate over all key-value-pairs of your map like this:
for (final Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// do whatever you need to do with key
}
If you're interested in a key for a certain value only - makes not much sense as the same value might be stored in a map with different keys - you will need to check for the value in the above loop until you found the key-value-pair of interest. E.g.:
if (Objects.equals(value, "A")) {
// do something with the key for value "A"
}
1. Solution for specific value:
This method returns keys for your value
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
Now all you have to do is to iterate through returned set and do what you want with variable which contains your key
for (Long key : set) {
String s = String.valueOf(key);
}
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 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.