Post Map<String, List<String>> - java

I have an Android application which has to sync clients data to server. I would like to post the data using a Map with one key and multiple data to store the columns (for example the name column will be like: key='name', value='John', 'Bill', 'Linda', etc.). Is it possible to post data in this format?
Thank you.

you can do it,
this can be helpful for you:
public static void main(String[] args) {
Scanner s = new Scanner(
"car toyota\n" +
"car bmw\n" +
"car honda\n" +
"fruit apple\n" +
"fruit banana\n" +
"computer acer\n" +
"computer asus\n" +
"computer ibm");
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
while (s.hasNext()) {
String key = s.next();
if (!map.containsKey(key))
map.put(key, new LinkedList<String>());
map.get(key).add(s.next());
}
System.out.println(map);
}

try this :
HashMap<String,List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("John");
list.add("Bill");
list.add("Linda");
map.put("name",list);
for (Map.Entry<String, List<String>> item:map.entrySet()){
List<String> newList = map.get(item.getKey());
}

Related

How to get values from the second column of a 2d array based on the fiest column value?

I have a Set of data. For example:
car accord
car civic
suv landcruzer
suv landrover
muv innova
I want store it in a scanner or hash map and retrieve the values based on the input.
If "car" is the input I want to pass URL+/accord and URL+/civic as its output
If "muv" is the input, I want to pass URL+/innova as its output
String URL = "www.abc.com";
String Vehicletype = "";
#DataProvider(name = "irLanguage")
public Object[][] lang() {
#SuppressWarnings("resource")
Scanner s = new Scanner(
"Car /accord/\n" +
"Car /civic/\n" +
"suv /landcruzer/\n" +
"suv /rangerover/\n" +
"muv /innova/\n");
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
while (s.hasNext()) {
String key = s.next();
if (!map.containsKey(key))
map.put(key, new LinkedList<String>());
map.get(key).add(s.next());
}
urlArray = map.get(vehicletype);
String[][] shades = new String[urlArray.size()][2];
for (int i = 0; i < urlArray.size(); i++) {
shades[i][0] = urlArray.get(i).toString();
shades[i][1] = URL + urlArray.get(i).toString();
lang = shades[i][0];
System.out.println(shades[i][0]);
}
return shades;
}
Here, the code is working fine. That is , if the input vehicle type is car then the output url is www.abc.com/accord/ and www.abc.com/civic/
and if the vehicle type is muv, it only returns www.abc.com/innova/ . This setup works fine for me. But, I wonder if there is any simpler method to do this.
Can anybody with good knowledge in java can help?
You have the right idea, I would build a HashMap that contains one Key (e.g. "car") and all the desired Values for that Key (e.g. "accord", "civic")
HashMap<String, ArrayList<String>> vehicles = new HashMap<String, ArrayList<String>>();
ArrayList<String> makes = new ArrayList<String>();
makes.add("accord");
makes.add("civic");
vehicles.put("car", makes);
makes.clear();
makes.add("landcruzer");
makes.add("rangerover");
vehicles.put("suv", makes);
makes.clear();
makes.add("innova");
vehicles.put("muv", makes);
makes.clear();
Now that you've got the vehicles HashMap built, you can fetch a Key and get all Values and build your URLs.
makes = vehicles.get("car");
for (String make : makes)
{
System.out.println("www.abc.com/" + make);
}

How to make 3 dimensional array in java?

I have a query string like
"1_timestamp=201612312&1_user=123&2_timestamp=20145333&2_user=5432";
But I want to make them in array like below.
array(
0 => (
timestamp = 201612312,
user = 123,
),
1 => (
timestamp = 201612312,
user = 123,
),
);
I'm sorry to show you php type of array though I'm new to java.
How do I make it something like that?
Thank you
This is the closest structure to what you are doing in php, and if your data has more fields it can be easily added to the Data class:
import java.util.ArrayList;
import java.util.List;
class Data {
int timestamp;
int user;
Data(int ts, int user) {
this.timestamp = ts;
this.user = user;
}
}
public class Test {
public static void main(String[] args) {
List<Data> data = new ArrayList<Data>();
Data d1 = new Data(201612312, 123);
Data d2 = new Data(201612312, 123);
data.add(d1);
data.add(d2);
System.out.println(data.get(1).user);
}
}
You can do it without writing a class. You can use it like this.
Map<String, String> map1 = new HashMap<String, String>();
map1.put("1_timestamp", "201612312");
map1.put("1_user", "123");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("2_timestamp", "20145333");
map2.put("2_user", "5432");
List<Map<String,String> mapList = new ArrayList<Map<String, String>>();
mapList.add(map1);
mapList.add(map2);
for (Map<String, String> map : list) {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}

How can i fetch all data present in Map<String,Map<String,String>> data structure?

i want to retrieve all data that are present in my data structure, which is of type Map of Maps.The data structure is mentioned below.
public static Map<String, Map<String, String>> hourlyMap = new HashMap<String, Map<String, String>>();
i need all the data that are stored in the map irrespective of key.
This may help you
Map<String,Map<String,String>> hourlyMap = new HashMap<String,Map<String,String>>();
for(Map<String,String> i:hourlyMap.values()){
// now i is a Map<String,String>
for(String str:i.values()){
// now str is a value of map i
System.out.println(str);
}
}
Try:
Set<String> allData = new HashSet<>(); // will contain all the values
for(Map<String, String> map : hourlyMap.values()) {
allData.addAll(map.values());
}
for (String outerKey: hourlyMap.keySet()) {
// outerKey holds the Key of the outer map
// the value will be the inner map - hourlyMap.get(outerKey)
System.out.println("Outer key: " + outerKey);
for (String innerKey: hourlyMap.get(outerKey).keySet()) {
// innerKey holds the Key of the inner map
System.out.println("Inner key: " + innerKey);
System.out.println("Inner value:" + hourlyMap.get(outerKey).get(innerKey));
}
}

Java HashMap associative multi dimensional array can not create or add elements

Okay so I have spent several hours trying to wrap my head around this concept of a HashMap in Java but am just not able to figure it out. I have looked at many tutorials but none seem to address my exact requirement and I cannot get it to work.
I am trying to create an associative multi dimensional array in Java (or something similar) so that I can both save to and retrieve from the array with keys that are Strings.
This is how I would do it in PHP and explains it best what I am trying to do:
//loop one - assign the names
myArray['en']['name'] = "english name";
myArray['fr']['name'] = "french name";
myArray['es']['name'] = "spanish name";
//loop two - assign the description
myArray['en']['desc'] = "english description";
myArray['fr']['desc'] = "french description";
myArray['es']['desc'] = "spanish description";
//loop three - assign the keywords
myArray['en']['keys'] = "english keywords";
myArray['fr']['keys'] = "french keywords";
myArray['es']['keys'] = "spanish keywords";
//later on in the code be able to retrive any value similar to this
english_name = myArray['en']['name'];
french_name = myArray['fr']['name'];
spanish_name = myArray['es']['name'];
This is what I tried in Java but it is not working:
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
myArray.put("en" , put("name", "english name")); //gives me "cannot find symbol" at second put
myArray.put("en" , ("name", "english name")); //gives me "')' expected" after second comma
So I am sure its something simple that I am missing but please point it out because this is very frustrating!
Thanks
EDIT:
So here is some working code on how I implemented the answer I accepted:
import java.util.*;
HashMap<String, HashMap<String, String>> finalArray = new HashMap<String, HashMap<String, String>>();
String[] langArray = {"en","fr","de","no","es"};
//Initialize each language key ahead of time
for(String lang : langArray) { // foreach lang in langArray
if (!finalArray.containsKey(lang)) {
finalArray.put(lang, new HashMap<String, String>());
}
}
//loop one - assign names
for(String lang : langArray) {
String theName = lang + " name"; //go get the name from somewhere
finalArray.get(lang).put("name", theName);
}
//loop two - assign description
for(String lang : langArray) {
String theDesc = lang + " description"; //go get the description from somewhere
finalArray.get(lang).put("desc", theDesc);
}
//loop three - assign keywords
for(String lang : langArray) {
String theKeys = lang + " keywords"; //go get the keywords from somewhere
finalArray.get(lang).put("keys", theKeys);
}
//display output
for(String lang : langArray) {
System.out.println("LANGUAGE: " + lang);
System.out.println(finalArray.get(lang).get("name"));
System.out.println(finalArray.get(lang).get("desc"));
System.out.println(finalArray.get(lang).get("keys"));
}
//example to retrieve/get values
String english_name = finalArray.get("en").get("name");
String french_desc = finalArray.get("fr").get("desc");
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
if (!myArray.containsKey("en")) {
myArray.put("en", new HashMap<String, String>());
}
myArray.get("en").put("name", "english name");
In Java you have to be explicit about when you are creating an object. In this case first we check if there is already a HashMap object stored in our outer HashMap under the key "en". If not, we create an empty one.
Now to put a new value into it we have to first get it from the outer HashMap, then put the new value.
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> value = new HashMap<String, String>();
value.put("name", "English name");
value.put("desc", "English description");
value.put("keys", "English keywords");
myArray.put("en" , value);
value = new HashMap<String, String>();
value.put("name", "French name");
value.put("desc", "French description");
value.put("keys", "French keywords");
myArray.put("fr" , value);
Unfortunately, there's no concise syntax for constructing populated maps in Java. You'll have to write it out long-hand. A separate helper method can make it a little simpler:
HashMap<String, String> makeMap(String name, String desc, String keys) {
HashMap<String, String> map = new HashMap<>();
// Before Java 7, above must be: new HashMap<String, String>();
map.put("name", name);
map.put("desc", desc);
map.put("keys", keys);
}
Then:
HashMap<String, HashMap<String, String>> myArray = new HashMap<>();
myArray.put("en",
makeMap("english name", "english description", "english keywords"));
// etc.
You would retrieve it with:
english_name = myArray.get("en").get("name");
import java.util.HashMap;
public class Main
{
public static void main(String[] args) {
// Creating array
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
// Setting values
for(int i=0; i<100;i++) {
myArray.put("key1"+i, new HashMap<String, String>());
myArray.get("key1"+i).put("key2"+i, "value"+i);
}
// Getting values
for(int i=0; i<100; i++) {
System.out.println(myArray.get("key1"+i).get("key2"+i));
}
}
}
I really liked the example by "dAv dEv", though he didn't really fill his double array of keys (I added a loop within a loop). I also like TreeMaps better than HashMaps because they aren't as random.
import java.util.Map;
import java.util.TreeMap;
TreeMap<String, TreeMap<String, String>> myArray =
new TreeMap<String, TreeMap<String, String>>();
String[] roles = { "Help Desk", "Administrator", "Super Use", ... };
String[] elements = { "Hydrogen", "Helium", "Lithium", "Beryllium", ... };
// Setting values TODO: read data values from Excel spreadsheet (or wherever)
for(String role : roles) {
myArray.put(role, new TreeMap<String, String>());
for (String elementName : elements) {
String value = Utils.getHumanName("first", true);
myArray.get(role).put(elementName, value);
}
}
// Getting values
for (Map.Entry<String,TreeMap<String,String>> entry1 : myArray.entrySet()) {
String key1 = entry1.getKey();
TreeMap<String,String> value1 = entry1.getValue();
for (Map.Entry<String,String> entry2 : value1.entrySet()) {
String key2 = entry2.getKey();
String value2 = entry2.getValue();
System.out.println("(" + key1 + ", " + key2 + ") = " +
myArray.get(key1).get(key2));
}
}
P.S. I used Utils.getHumanName() as my data generator. You will need to use your own.

Is there a convenient way to convert comma separated string to hashmap

String format is (not json format):
a="0PN5J17HBGZHT7JJ3X82", b="frJIUN8DYpKDtOLCwo/yzg="
I want convert this string to a HashMap:
key a with value 0PN5J17HBGZHT7JJ3X82
key b with value frJIUN8DYpKDtOLCwo/yzg=
Is there a convenient way? Thanks
What I've tried:
Map<String, String> map = new HashMap<String, String>();
String s = "a=\"00PN5J17HBGZHT7JJ3X82\",b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
String []tmp = StringUtils.split(s,',');
for (String v : tmp) {
String[] t = StringUtils.split(v,'=');
map.put(t[0], t[1]);
}
I get this result:
key a with value "0PN5J17HBGZHT7JJ3X82"
key b with value "frJIUN8DYpKDtOLCwo/yzg
for key a, the start and end double quotation marks(") is unwanted; for key b, the start double quotation marks(") is unwanted and the last equals sign(=) is missing.
Sorry for my poor english.
Probably you don't care that it's a HashMap, just a Map, so this will do it, since Properties implements Map:
import java.io.StringReader;
import java.util.*;
public class Strings {
public static void main(String[] args) throws Exception {
String input = "a=\"0PN5J17HBGZHT7JJ3X82\", b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
String propertiesFormat = input.replaceAll(",", "\n");
Properties properties = new Properties();
properties.load(new StringReader(propertiesFormat));
System.out.println(properties);
}
}
Output:
{b="frJIUN8DYpKDtOLCwo/yzg=", a="0PN5J17HBGZHT7JJ3X82"}
If you absolutely need a HashMap, you can construct one with the Properties object as input: new HashMap(properties).
Added few changes in Ryan's code
public static void main(String[] args) throws Exception {
String input = "a=\"0PN5J17HBGZHT7JJ3X82\", b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
input=input.replaceAll("\"", "");
String propertiesFormat = input.replaceAll(",", "\n");
Properties properties = new Properties();
properties.load(new StringReader(propertiesFormat));
Set<Entry<Object, Object>> entrySet = properties.entrySet();
HashMap<String,String > map = new HashMap<String, String>();
for (Iterator<Entry<Object, Object>> it = entrySet.iterator(); it.hasNext();) {
Entry<Object,Object> entry = it.next();
map.put((String)entry.getKey(), (String)entry.getValue());
}
System.out.println(map);
}
Split the String on the Basis of commas (",") and then with with ("=")
String s = "Comma Separated String";
HashMap<String, String> map = new HashMap<String, String>();
String[] arr = s.split(",");
String[] arStr = arr.split("=");
map.put(arr[0], arr[1]);
You can also use the regex as below.
Map<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
for ( int i=0; i+2 <= split.length; i+=2 ){
data.put( split[i], split[i+1] );
}
return data;

Categories