How to get Result of LinkedHashMap within Inverted commas [duplicate] - java

This question already has answers here:
How to convert HashMap to json Array in android?
(5 answers)
Closed 5 years ago.
I am developing an Android app in which I have to send LinkedHashMap results by API but the problem what I am getting is format of result is different. How can I put keys and values both in inverted commas?
I'm getting result like this:
list: {0=816444014066, 1=747083010945, 2=816444010969}
And I want result like this:
list: {"0" : "816444014066","1" : "747083010945","2" : "816444010969"}
How to change the format of result?

Use My Answer. It worked for me.
LinkedHashMap<String, String> data = new LinkedHashMap<String, String>();
// Instantiate a new Gson instance.
Gson gson = new Gson();
// Convert the ordered map into an ordered string.
String json = gson.toJson(data, LinkedHashMap.class);
// Print ordered string.
Log.e("list", ""+json); // {"0" : "816444014066","1" : "747083010945","2" : "816444010969"}

To get the quotes you need to make your keys and values String in your LinkedHashMap
Edit:
maybe what you need is already provided in this answer

In Java you can put quotes to String with :
String value = " \"1\" ";
You could do it like this:
Map<String, String> linkedmap = new LinkedHashMap<>();
linkedHashMap.put(setQuotes("1"), setQuotes("5445454"));
public static String setQuotes(String value){
String result = "";
if(!value.isEmpty()){
result = "\"" + value + "\"";
}
return result;
}
If you print it in the console, it returns:
{"1"="5445454"}

I think that possibility is to create your own Map class that extends LinkedHashMap and to create and implement in it method with behavior similar to behavior of toString() method. This link might help you to get started with implementation of that method:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/AbstractMap.java#AbstractMap.toString%28%29

Related

How to get value from List<> giving String as variable name [duplicate]

This question already has answers here:
Java: How can I access a class's field by a name stored in a variable?
(2 answers)
Closed 1 year ago.
I have a list based on database.
List<Contact> contactList;
There are many variables. For example:
String name;
String phone;
Can I get a specific value in way like this?
String var = "name";
String val = contactList.get(0).var <--- this Sting variable here
Is any way to do something like this? I don't want to write x10 :
if(var == "name"){
String val = contactList.get(0).name;
}
I think is way for do it, but I'm newbie, sorry if something is wrong with my question.
I will be very grateful for help.
Working code:
Thank you for answer. This is full code if someone will be looking for answer in the future:
private Map<String, Function<Contact, String>> map;
map = new HashMap<>();
map.put("Name", c -> c.name);
map.put("Phone", c -> c.phone);
map.put("Email", c -> c.email);
String some_val = map.get(second_value).apply(contactList.get(position));
You need a Map<String, Function<Contact, String>> containing method references, keyed by the property name.
For example:
// Construct this once, store in a static final field.
Map<String, Function<Contact, String> map =
Map.of("name", c -> c.name /* etc for other fields */);
// Then, when you want to get the value:
String val = map.get(var).apply(contactList.get(0));

Java: How to print the String value of a Map element? [duplicate]

This question already has answers here:
get string value from HashMap depending on key name
(10 answers)
Closed 3 years ago.
Could someone tell me how to get or print the String value of a map element?
The below code results in "The method values() is undefined for the type String."
I also tried .getValue() but the outcome is the same.
Thanks in advance!
Map<Integer, String> mapName = new HashMap<>();
mapName.put(0, "description_0");
mapName.put(1, "description_1");
for (Integer i : mapName.keySet()){
System.out.println(mapName.get(i).values());
}
Answer provided by #Lino.
for(String s : mapName.values()) System.out.println(s);
If you want to use stream:
mapName.entrySet().stream().forEach(elem-> System.out.println(elem));
This will allow you to use all the features of stream such as filtering,collecting , reducing etc.
https://www.geeksforgeeks.org/stream-map-java-examples/

Generate a Get query string in Java

I want to generate a Get query string in java like so
www.example.com/somethingToGet?key1=value&key2=value....
So my method has 2 parameters the base url(www.example.com/somethingToGet) is the first argument and the 2nd argument is a map data structure. I want to iterate over the map and generate a string like so
key1=value&key2=value....
It shouldn't end with ampersand.
I don't want to use any built in functions, I want to know the logic how such strings are generated.
Something like this:
public static String getQuery(String base, java.util.Map<String, String> map) {
StringBuilder str = new StringBuilder(base);
str.append('?');
boolean first = true;
for (java.util.Map.Entry<String, String> e : map.entrySet()) {
if (first)
first = false;
else
str.append('&');
str.append(e.getKey());
str.append('=');
str.append(e.getValue());
}
return str.toString();
}
You can also use the format method in URLEncoder class from the Apache HttpComponents library to create a query string. As per the documentation it
Returns a String that is suitable for use as an application/x-www-form-urlencoded list of parameters in an HTTP PUT or HTTP POST.

Good practice for method in java

I have a method that read from database and get some string there. According what I get I will override that string for another that I already know. For example:
str → string
bin → binary
and so on..
My question is, what is the best practice for doing this? Of course I already thought about if's...
if (str.equals("str"))
str = "string";
A file that have this things pre-defined, a multi-dimensional array, etc.. But this all seems a quite newbie, so what do you recommend? What is the best way?
Use a Map:
// create a map that maps abbreviated strings to their replacement text
Map<String, String> abbreviationMap = new HashMap<String, String>();
// populate the map with some values
abbreviationMap.put("str", "string");
abbreviationMap.put("bin", "binary");
abbreviationMap.put("txt", "text");
// get a string from the database and replace it with the value from the map
String fromDB = // get string from database
String fullText = abbreviationMap.get(fromDB);
You can read more about Maps here.
You could use a map, for example:
Map<String, String> map = new HashMap<String, String>();
map.put("str", "string");
map.put("bin", "binary");
// ...
String input = ...;
String output = map.get(input); // this could be null, if it doesn't exist in the map
Map is a good option as people have suggested. The other option which I normally consider in this scenario is Enum. It gives you an additional capability of adding behavior for a combination.

Can you reference a java variable from a string?

Hi I have a strange question about java. I will leave out the background info so as not to complicate it. If you have a variable named fname. And say you have a function returning a String that is "fname". Is there a way to say reference the identifier fname via the String "fname". The idea would be something like "fname".toIdentifier() = value but obviously toIdentifier isn't a real method.
I suppose a bit of background mite help. Basically I have a string "fname" mapped to another string "the value of fname". And I want a way to quickly say the variable fname = the value of the key "fname" from the map. I'm getting the key value pair from iterating over a map of cookies in the form . And I don't want to do "if key = "fname" set fname to "value of fname" because I have a ton of variables that need to be set that way. I'd rather do something like currentkey.toIdentifer = thevalue. Weird question maybe I'm overlooking a much easier way to approach this.
Why don't you just use a simple hashmap for this?
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "someValue");
...
String value = mapping.get(key); //key could be "fname"
In a way you're describing what reflection is used for:
You refer to an object's fields and methods by name.
Java Reflection
However, most of the time when people ask a question like this, they're better off solving their problem by re-working their design and taking advantage of data structures like Maps.
Here's some code that shows how to create a Map from two arrays:
String[] keyArray = { "one", "two", "three" };
String[] valArray = { "foo", "bar", "bazzz" };
// create a new HashMap that maps Strings to Strings
Map<String, String> exampleMap = new HashMap<String, String>();
// create a map from the two arrays above
for (int i = 0; i < keyArray.length; i++) {
String theKey = keyArray[i];
String theVal = valArray[i];
exampleMap.put(theKey, theVal);
}
// print the contents of our new map
for (String loopKey : exampleMap.keySet()) {
String loopVal = exampleMap.get(loopKey);
System.out.println(loopKey + ": " + loopVal);
}
Here's a link to the JavaDoc for Map.

Categories