ArrayList<HashMap<String,String>> to String[] - java

i have data fetched from my webservice in
ArrayList<HashMap<String,String>>
Now i want to convert each object of the above to
String[]
how do i do this?
any help would be much appreciated!

try
ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
HashMap<String, String> n = new HashMap<String, String>();
n.put("a", "a");
n.put("b", "b");
test.add(n);
HashMap<String, String> m = test.get(0);//it will get the first HashMap Stored in array list
String strArr[] = new String[m.size()];
int i = 0;
for (HashMap<String, String> hash : test) {
for (String current : hash.values()) {
strArr[i] = current;
i++;
}
}

The uses for an Hashmap should be an Index of HashValues for finding the values much faster. I don't know why you have Key and Values as Strings but if you only need the values you can do it like that:
ArrayList<HashMap<String, String>> test = new ArrayList<>();
String sum = "";
for (HashMap<String, String> hash : test) {
for (String current : hash.values()) {
sum = sum + current + "<#>";
}
}
String[] arr = sum.split("<#>");
It's not a nice way but the request isn't it too ;)

ArrayList<HashMap<String, String>> meterList = controller.getMeter();
HashMap<String, String> mtiti = meterList.get(0);//it will get the first HashMap Stored in array list
String[] strMeter = new String[mtiti.size()];
String meter = "";
for (HashMap<String, String> hash : meterList) {
for (String current : hash.values()) {
meter = meter + current + "<#>";
}
}
String[] arr = meter.split("<#>");

Related

ArrayList of HashMaps to string, and then back to ArrayList of HashMaps

I have a ArrayList<HashMap<String,String>> that I am using the toString() method on to store in a database.
Here is the code that I use to store it the toString() to a database (it works):
HashMap<String, String> commentsHash = null;
ArrayList<HashMap<String, String>> test2 = new ArrayList<HashMap<String, String>>();
for (int i=0; i < test.size(); i++)
{
String timestamp = test.get(i).get("timestamp");
String last_name = test.get(i).get("last_name");
String first_name = test.get(i).get("first_name");
String comment = test.get(i).get("comment");
commentsHash = new HashMap<String, String>();
commentsHash.put("creation_timestamp", timestamp);
commentsHash.put("first_name", first_name);
commentsHash.put("last_name", last_name);
commentsHash.put("comment", comment);
test2.add(commentsHash);
}
dbHelper.addCommentsToMyLiPost(Integer.parseInt(sqlId), test2.toString());
Here is the method I want to use to convert a string to a HashMap<String, String>:
protected HashMap<String,String> convertToStringToHashMap(String text){
HashMap<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
for ( int i=1; i+2 <= split.length; i+=2 ){
data.put( split[i], split[i+1] );
}
return data;
}
I have tried using .split(",") on the string to split the string into 2 parts, but instead of returning two, it returns 8.
Here is what the toString() method prints. It is an ArrayList of HashMaps, and I am trying to grab the two HashMaps that are inside of the ArrayList.
[{comment=hello, last_name=u1, first_name=u1, creation_timestamp=1404938643772}, {comment=hello2, last_name=u2, first_name=u2, creation_timestamp=1404963221598}]
In convertToStringToHashMap, when you put your data into HashMap, the old value will be replaced since they have same key for each records, such as comment, last_name, etc.
public static Map<String, Map<String, String>> convertToStringToHashMap(String text)
{
Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
Map<String, String> data = new HashMap<String, String>();
int gap = 8;
int key = 1;
for (int i = 1; i + 2 <= split.length; i += 2)
{
data.put(split[i], split[i+1]);
if((i + 1) % gap == 0)
{
map.put(String.valueOf(key++), data);
data = new HashMap<String, String>();
data.clear();
}
}
return map;
}
This will return a Map:
2={first_name=u2, last_name=u2, comment=hello2, creation_timestamp=1404963221598}
1={first_name=u1, last_name=u1, comment=hello, creation_timestamp=1404938643772}
This program will recreate the whole list from the database entry
Pattern firstPat = Pattern.compile("\\{.*?\\}");
Matcher firstMat = firstPat.matcher(text);
ArrayList<HashMap<String, String>> list = new ArrayList<>();
while(firstMat.find()){
HashMap<String, String> map = new HashMap<>();
String assignStrings = firstMat.group();
String [] assignGroups = assignStrings.substring(1,assignStrings.length()-1).split("\\s*\\,\\s*");
for(String assign:assignGroups){
String [] parts = assign.split("\\=");
map.put(parts[0], parts[1]);
}
list.add(map);
}
return list

Merging of 3 Hashtable into 1 based on common values they contain

I have 3 vector as given below.Here Vector1, Vector2, Vector3 will not be of same size.below given is an ideal situation that will occur some time only.It might be possible that vector2 only contain one extra {} with d=3,... and vector1 and Vector3 will don't have that(d=3) entry.
Vector1 := [{a=Prity, b=Joshi, c=Pyarelal, d=1},{a=tiny, b=darji, c=Mohandas, d=2}]
Vector2 := [{e=age-29, f=height-5, d=1},{e=age-52, f=height-6, d=2}]
Vector3 := [{g=pet-dog, d=1},{g=pet-cat, d=2}]
I want a vector that will merge values and give me final vector as displayed below
Vector4 := [{a=Prity, b=Joshi, c=Pyarelal, d=1,e=age-29, f=height-5, g=pet-dog}, {a=tiny, b=darji, c=Mohandas, d=2, e=age-52, f=height-6, g=pet-cat}]
I implemented one logic but it is time consuming.Does anyone has better option ?????
int columnSize = Vector1.size() > Vector2.size() ? Vector1.size()
: Vector2.size();
Hashtable finalHash[] = new Hashtable[columnSize];
for (i = 0; i < Vector1.size(); i++) {
finalHash[i] = (Hashtable) Vector1.elementAt(i);
for (int z = 0; z < Vector2.size(); z++) {
Hashtable hashtwo = (Hashtable) Vector2.elementAt(z);
if (hashtwo.containsValue(finalHash[i]
.get("TQM_QUOTE_INCEPTION_DATE"))) {
finalHash[i].putAll(hashtwo);
Vector2.removeElementAt(z);
}
}
for (int z = 0; z < Vector3.size(); z++) {
Hashtable hashduerenew = (Hashtable) Vector3.elementAt(z);
if (hashduerenew.containsValue(finalHash[i]
.get("TQM_QUOTE_INCEPTION_DATE"))) {
finalHash[i].putAll(hashduerenew);
Vector3.removeElementAt(z);
}
}
}
columnSize = Vector2.size() > Vector3.size() ? Vector2.size() : Vector3
.size();
Hashtable finalHashtable = new Hashtable();
for (int t = 0; t < Vector2.size(); t++, i++) {
finalHashtable = (Hashtable) Vector2.elementAt(t);
for (int z = 0; z < Vector3.size(); z++) {
Hashtable hashtwo = (Hashtable) Vector3.elementAt(z);
if (hashtwo.containsValue(finalHashtable
.get("TQM_QUOTE_INCEPTION_DATE"))) {
finalHash[i].putAll(hashtwo);
Vector3.removeElementAt(z);
break;
}
}
finalHash[i].putAll(finalHashtable);
Vector2.removeElementAt(t);
}
int t = 0;
while (t < Vector3.size()) {
finalHash[i] = (Hashtable) Vector3.elementAt(t);
t++;
i++;
}
I think he wanted something like this:
private static Vector<Hashtable<Character, String>> vector1;
private static Vector<Hashtable<Character, String>> vector2;
private static Vector<Hashtable<Character, String>> vector3;
public static void main(final String[] args) {
setUp();
// Your final vector
Vector<Hashtable<Character, String>> mergedVector = new Vector<Hashtable<Character, String>>();
// Considering every vector has the same size
addToMerged(mergedVector, vector1);
addToMerged(mergedVector, vector2);
addToMerged(mergedVector, vector3);
// Print the result
for (Hashtable<Character, String> hash : mergedVector) {
for (Entry<Character, String> set : hash.entrySet()) {
System.out.println("KEY: " + set.getKey() + ", VALUE: "
+ set.getValue());
}
System.out.println("\nNext hashtable.\n");
}
}
private static void setUp() {
vector1 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash11 = new Hashtable<Character, String>();
hash11.put('a', "Prity");
hash11.put('b', "Joshi");
hash11.put('c', "Pyarelal");
hash11.put('d', "1");
vector1.add(hash11);
Hashtable<Character, String> hash12 = new Hashtable<Character, String>();
hash12.put('a', "tiny");
hash12.put('b', "darji");
hash12.put('c', "Mohandas");
hash12.put('d', "2");
vector1.add(hash12);
vector2 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash21 = new Hashtable<Character, String>();
hash21.put('e', "age-29");
hash21.put('f', "height-5");
hash21.put('d', "1");
vector2.add(hash21);
Hashtable<Character, String> hash22 = new Hashtable<Character, String>();
hash22.put('e', "age-52");
hash22.put('f', "height-6");
hash22.put('d', "2");
vector2.add(hash22);
vector3 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash31 = new Hashtable<Character, String>();
hash31.put('g', "pet-dog");
hash31.put('d', "1");
vector3.add(hash31);
Hashtable<Character, String> hash32 = new Hashtable<Character, String>();
hash32.put('g', "pet-cat");
hash32.put('d', "2");
vector3.add(hash32);
}
private static void addToMerged(
final Vector<Hashtable<Character, String>> mergedVector,
final Vector<Hashtable<Character, String>> vector) {
for (int i = 0; i < vector.size(); i++) {
Hashtable<Character, String> hashtable = vector.get(i);
for (Entry<Character, String> entrySet : hashtable.entrySet()) {
boolean added = false;
for (int j = 0; j < mergedVector.size() && !added; j++) {
Hashtable<Character, String> hashtable2 = mergedVector
.get(j);
if (!hashtable2.containsKey(entrySet.getKey())) {
hashtable2.put(entrySet.getKey(), entrySet.getValue());
added = true;
break;
} else if (hashtable2.get(entrySet.getKey()).equals(
entrySet.getValue())) {
added = true;
break;
}
}
if (!added) {
Hashtable<Character, String> hashtable2 = new Hashtable<>();
hashtable2.put(entrySet.getKey(), entrySet.getValue());
mergedVector.add(hashtable2);
}
}
}
}
Hashtable doesn't keep the order in which you add the elements, so your vectors originally aren't going to look as you wrote them in your post, if you want to archieve that you will have to use LinkedHashTable.
Taking into account the comment before, you can merge your vectors like this:
public static void main(String[] args) {
Vector<Hashtable<Character, String>> vector1 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash11 = new Hashtable<Character, String>();
hash11.put('a', "Prity");
hash11.put('b', "Joshi");
hash11.put('c', "Pyarelal");
hash11.put('d', "1");
vector1.add(hash11);
Hashtable<Character, String> hash12 = new Hashtable<Character, String>();
hash12.put('a', "tiny");
hash12.put('b', "darji");
hash12.put('c', "Mohandas");
hash12.put('d', "2");
vector1.add(hash12);
Vector<Hashtable<Character, String>> vector2 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash21 = new Hashtable<Character, String>();
hash21.put('e', "age-29");
hash21.put('f', "height-5");
hash21.put('d', "1");
vector2.add(hash21);
Hashtable<Character, String> hash22 = new Hashtable<Character, String>();
hash22.put('e', "age-52");
hash22.put('f', "height-6");
hash22.put('d', "2");
vector2.add(hash22);
Vector<Hashtable<Character, String>> vector3 = new Vector<Hashtable<Character, String>>();
Hashtable<Character, String> hash31 = new Hashtable<Character, String>();
hash31.put('g', "pet-dog");
hash31.put('d', "1");
vector3.add(hash31);
Hashtable<Character, String> hash32 = new Hashtable<Character, String>();
hash32.put('g', "pet-cat");
hash32.put('d', "2");
vector3.add(hash32);
// Your final vector
Vector<Hashtable<Character, String>> mergedVector = new Vector<Hashtable<Character, String>>();
// Considering every vector has the same size
for (int i = 0; i < vector1.size(); i++) {
mergedVector.add(vector1.get(i));
mergedVector.add(vector2.get(i));
mergedVector.add(vector3.get(i));
}
// Print the result
for (Hashtable<Character, String> hash : mergedVector) {
for (Entry<Character, String> set : hash.entrySet())
System.out.println("KEY: " + set.getKey() + ", VALUE: " + set.getValue());
System.out.println("\nNext hashtable.\n");
}
}

How to get the frequently occuring words from the text extracted using tika

I have extracted text for multiple file formats(pdf,html,doc) using below code(using tika)
File file1 = new File("c://sample.pdf);
InputStream input = new FileInputStream(file1);
BodyContentHandler handler = new BodyContentHandler(10*1024*1024);
JSONObject obj = new JSONObject();
obj.put("Content",handler.toString());
Now my requirement is to get the frequently occurring words from the extracted content, can u please suggest me how to do this.
Thanks
Here's a function to the most frequent word.
You need to pass the content to the function, and you get the frequently occurring word.
String getMostFrequentWord(String input) {
String[] words = input.split(" ");
// Create a dictionary using word as key, and frequency as value
Map<String, Integer> dictionary = new HashMap<String, Integer>();
for (String word : words) {
if (dictionary.containsKey(word)) {
int frequency = dictionary.get(word);
dictionary.put(word, frequency + 1);
} else {
dictionary.put(word, 1);
}
}
int max = 0;
String mostFrequentWord = "";
Set<Entry<String, Integer>> set = dictionary.entrySet();
for (Entry<String, Integer> entry : set) {
if (entry.getValue() > max) {
max = entry.getValue();
mostFrequentWord = entry.getKey();
}
}
return mostFrequentWord;
}
The algorithm is O(n) so the performance should be okay.

how to get hashmap content of arraylist in java?

I am using the following code to save hashmap content into arraylist.
HashMap jediSaber = new HashMap();
ArrayList<HashMap> valuesList = new ArrayList();
for(int i = 0; i< 4;i++) {
jediSaber.put("white","white_name"+i);
jediSaber.put("blue","blue_name"+i);
valuesList.add(i, jediSaber);
System.out.println("list ontent:"+i+":"+valuesList.get(i).values());
}
`
output is as follows:
list content:0:[blue_name0, white_name0]
list content:1:[blue_name1, white_name1]
list content:2:[blue_name2, white_name2]
list content:3:[blue_name3, white_name3]
When i try to display the content of arraylist in outside with the following code,
System.out.println("list content:");
for(int i = 0;i<valuesList.size();i++){
System.out.println("list:"+i+":"+valuesList.get(i).values());
}
It is showing the following output,
list content:0:[blue_name3, white_name3]
list content:1:[blue_name3, white_name3]
list content:2:[blue_name3, white_name3]
list content:3:[blue_name3, white_name3]
My problem is i need to display the content of arraylist of hashmap.
I think something i missed in second part. Can anybody help me to solve this minor issue?
Thanks in advance!!..
This is adding the same HashMap each time to the ArrayList:
valuesList.add(i, jediSaber);
Create a new HashMap each time within the for and add it:
List<HashMap<String, String>> valuesList =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 4; i++)
{
HashMap<String, String> m = new HashMap<String, String>();
m.put("white", "white_name" + i);
m.put("blue", "blue_name" + i);
valuesList.add(m);
}
System.out.println(valuesList.toString());
List<Map> valuesList = new ArrayList();
for (int i = 0; i < 4; i++) {
Map<Object, Object> jediSaber = new HashMap<>();
jediSaber.put("white", "white_name" + i);
jediSaber.put("blue", "blue_name" + i);
valuesList.add(jediSaber);
Set<Entry<Object, Object>> entrySet = jediSaber.entrySet();
for (Entry<Object, Object> entry : entrySet) {
System.out.println(entry.getKey() + "-" + entry.getValue());
}
}
Try pulling jediSaber inside your for loop, like so:
for(int i = 0; i < 4; i++) {
Map<String, String> jediSaber = new HashMap<String, String>();
You should also parameterize valuesList too:
List<Map<String, String>> valuesList = new ArrayList<Map<String, String>>();
P.S. There's no need to call add(i, jediSaber) with the index argument: valuesList.add(jediSaber) will have the same effect.

sorting data in a file

I am facing a problem in sorting. The format of data is:
b4 S0_c5 t 0.426544
b6 S1_c5 t 1.51049
b13 S0_c5 t 0.594502
b13 S1_c5 t 0.537496
b15 S1_c5 t 0.884126
b18 S0_c5 t 0.500933
b19 S1_c5 t 0.628472
b22 S0_c5 t 0.437718
and required result is:
S0_c5 b13 0.594502 b18 0.500933 b22 0.437718 b4 0.426544
S1_c5 b6 1.51049 b15 0.884126 b19 0.628472 b13 0.537496
the value is also in descending order. Thanks in advance.
Put the data in a TreeList<String, List<String>> (because it's sorted) where the second word from a sequence is the key, and the value a list of strings, then sort each list you obtain this way:
Map<String, List<String[]>> map = new TreeMap<String, List<String[]>>();
for (String s : strings) {
String[] tokens = s.split(" ");
List<String[]> values = map.get(tokens[1]);
if (values == null) {
values = new ArrayList<String[]>();
map.put(tokens[1], values);
}
values.add(new String[]{tokens[0], tokens[3]});
}
for (String key : map.keySet()) {
List<String[]> list = map.get(key);
Collections.sort(list, new Comparator<String[]>() {
#Override
public int compare(String[] o1, String[] o2) {
return o1[1].compareTo(o2[1]) * -1;
}
});
System.out.print(key + " ");
for (String[] s : list) {
System.out.print(s[0] + " " + s[1]);
}
System.out.println();
}
Update:
E.g. to read from a file:
BufferedReader br;
try {
br = new BufferedReader(new FileReader("d:/temp/r.res"));
Map<String, List<String[]>> map = new TreeMap<String, List<String[]>>();
while (br.ready()) {
String s = br.readLine();
if (!s.trim().isEmpty()) {
String[] tokens = s.split(" ");
List<String[]> values = map.get(tokens[1]);
if (values == null) {
values = new ArrayList<String[]>();
map.put(tokens[1], values);
}
values.add(new String[]{tokens[0], tokens[3]});
}
}
} finally {
br.close();
}
Split your data by ' '.
Create a HashMap<String, List<String[]>>
For Each Row:
Look if the Map Contains the Key (split[1])
If there is no List at that key, create one
add split[1], split to the correct list
Iterate through your map and order each List
Output the data
Put the data into a List and use Collections.sort() to sort it.
there is a class in the JDK just for the purpose of having a sorted list. It is named (somewhat out of order with the other Sorted* interfaces) "java.util.PriorityQueue". It can sort either Comparables or using a Comparator.
The difference with a List sorted using Collections.sort(...) is that this will maintain order at all times, and have good insertion performance by using a heap data structure, where inserting in a sorted ArrayList will be O(n) (i.e., using binary search and move).
However other than List, PriorityQueue does not support indexed access (get(5)), the only way to access items in a heap is to take them out, one at a time (thus the name PriorityQueue).
Try this. It will work.
private void ReadTextFile(String filename) throws IOException
{
BufferedReader br = null;
FileInputStream fin = null;
fin = new FileInputStream(filename);
br =new BufferedReader(new InputStreamReader(fin));
Map<String,String> stringStringMap = new TreeMap<String, String>(Collections.reverseOrder());
while ((line = br.readLine()) != null) {
stringStringMap.put(line.split(" ")[3],line);
}
Collection<String> collection = stringStringMap.values();
Map<String, List<String>> map = new TreeMap<String, List<String>>();
Iterator<String> iterator = collection.iterator();
while(iterator.hasNext()){
String[] tokens = iterator.next().split(" ");
List<String> values = map.get(tokens[1]);
if (values == null) {
values = new ArrayList<String>();
map.put(tokens[1], values);
}
values.add(tokens[0] + " " + tokens[3]);
}
for (List<String> mapList : map.values()) {
Collections.sort(mapList);
}
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
}

Categories

Resources