.asFormUrlEncoded() to retrieve data from hashMap<String, String> - java

I'm sending a video file along with some user details to my play framework application using MultipartRequest, the user details are added to a hashmap Map<String, String> myMap;on the server side I have retrieved my video file using .asMultipartFormData();
I was trying to retrieve my map using .asFormUrlEncoded(); but that uses Map<String, String[]>
So I've only been able to retrieve one value from my hash map, if I try to retrieve anymore using this code
for(int i =0; i < myMap.size(); i++){
String param = "param" + (i + 1);
System.out.println(myMap.get(param)[i]);
}
I get an arrayOutOfBounds error, is there an alternative solution to retrieve the data from the MultipartFormData, or can I implement my loop differently?
maybe I shouldn't be using .asFormUrlEncoded();at all to retrieve the hashmap?
EDIT
I've modifed my code to use an iterator
Iterator<String> myVeryOwnIterator = myMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String[] value= myMap.get(key);
System.out.println(key + " " + value);
}
This prints my key, but returns Ljava.lang.String;# for the values, I think this is because the .asFormUrlEncoded(); is expecting a <String, string[]>, but my hashMap uses <String, String> any solution to this?

This was the solution:
Iterator<String> myVeryOwnIterator = myMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String[] value= myMap.get(key);
System.out.println(key + " " + value[0]);
}

Related

MultiValueMap get values

hi im trying to access a MultiValueMap which is in a Hashmap
this is my HashMap insideprojectDetails HashMap
private HashMap<String, ClassDetails> classDetailsMap = new HashMap<String, ClassDetails>();
inside that classDetailsMap i have MultiValueMap called methodDetailsMap
private MultiMap<String, MethodDetails> methodDetailsMap = new MultiValueMap<String, MethodDetails>();
when im trying to access the methodDetailsMap by
Set<String> methodNamesSet = projectDetails.getClassDetailsMap().get(cls).getMethodDetailsMap().keySet();
String[] methodNames = methodNamesSet.toArray(new String[0]);
for (int i = 0; i < methodNames.length; i++) {
String methodName = methodNames[i];
System.out.println(cls + " "+methodName);
//codes used to access key values
Collection coll = (Collection) methodNamesSet.get(methodName);
System.out.println(cls + " "+methodNamesSet.get(methodName));
}
i get a error get saying cannot resolve method get(java.lang.String)
is there any way to access the MultiValueMap
Its a compilation error with your code. There is no get method in Set.
methodNamesSet.get(methodName)
To get method details, first loop through the set and then get method details from methodDetailsMap as below.
MultiValueMap<String, MethodDetails> methodDetailsMap = projectDetails.getClassDetailsMap().get(0).getMethodDetailsMap();
Set<String> methodNamesSet = methodDetailsMap.keySet();
for(String str: methodNamesSet) {
System.out.println(methodDetailsMap.get(str));
}
I read your code and as I understand first you need to get all method names of cls class then you want to get them one by one. So in the for loop you need to get from the getMethodDetailsMap().This will help you:
for (int i = 0; i < methodNames.length; i++) {
String methodName = methodNames[i];
System.out.println(cls + " "+methodName);
//codes used to access key values
Collection coll = projectDetails.getClassDetailsMap().get(cls).getMethodDetailsMap().get(methodName);
System.out.println(cls + " "+methodNamesSet.get(methodName));
}

3D HashMap java get entries

I'm currently try to build my own elasticsearch (with less more capabilities and experience) to filter my firebase database, I don't use elasticsearch nor Algolia because I want to make all by myself.
Right now I've come up with this method:
1) get all keywords from my child nodes in firebase
2) add them in a 3D HashMap
For now it arranges my data like I want:
Map<String, Map<String, Map<String, String>>> map = new HashMap<>();
Ex.: "Restaurants" { "Some restaurant Name" { "keywords": "Some,keywords,here" }
All I want to do now is to print all values as a way to get further in my code.
Here's how I'm trying to print:
for (Map.Entry<String, Map<String, Map<String, String>>> entry : map.entrySet()) {
Log.w("MAP =====> ", entry.getKey() + ": " + entry.getValue());
for (Map.Entry<String, Map<String, String>> entry1 : map.get(entry.getKey()).entrySet()) {
Log.w("MAP2 =====> ", entry1.getKey() + ": " + entry1.getValue());
for (Map.Entry<String, String> entry2 : map.get(entry.getKey()).get(entry1.getKey()).entrySet()) {
Log.w("MAP3 =====> ", entry2.getKey() + ": " + entry2.getValue());
}
}
}
I can't seem to be able to go further than the first for loop...
Here's my log:
W/MAP =====>: Restaurants: {}
W/MAP =====>: Hikes: {}
W/MAP =====>: Sports: {}
As you can see, Logs for "MAP2" and "MAP3" are not showing, How can I iterate trough all?
Thanks in advance,
Good day/evening/night!
PS.: I know that firebase querying exists, I don't want to use .startAt() or .endAt() ,etc.

Removing Values From a Map in a loop

I am trying to compare two maps and remove values from one map that are contained in a second map. Here is the code:
HashMap<String, String> firstMap = new HashMap<>();
HashMap<String, String> secondMap = new HashMap<>();
firstMap.put("keyOne", "valueOne");
firstMap.put("keyTwo", "valueTwo");
firstMap.put("THIS KEY WILL BE REMOVED", "valueThree");
System.out.println("\nMAP ONE\n" + firstMap + "\n");
secondMap.put("keyOne", "valueOne");
secondMap.put("keyTwo", "valueTwo");
System.out.println("\nMAP TWO\n" + secondMap + "\n");
Iterator<String> firstMapIterator = firstMap.keySet().iterator();
if(!firstMap.equals(secondMap)){
firstMapIterator.next();
for(String key : firstMap.keySet()){
if(firstMap.containsKey(key) && !secondMap.containsKey(key)){
firstMapIterator.remove();
break;
}
}
}
System.out.println("\nMAP ONE MATCHING MAP TWO?\n" + firstMap + "\n");
Now, the code does remove an element from the map but not the one I was expecting. As you can see in the code in firstMap I have entered a third key of which is the one I expect to be removed. However, this is the final contents of firstMapI seem to be getting.
{keyOne=valueOne, THIS KEY WILL BE REMOVED=valueThree}
Any ideas? Thanks
Edit: The goal of this code is to:
- Compare two maps
- Increment through each key
- Remove key from firstMap if it is not found in secondMap
You can do this in just one line:
HashMap<String, String> firstMap = new HashMap<>();
HashMap<String, String> secondMap = new HashMap<>();
firstMap.put("keyOne", "valueOne");
firstMap.put("keyTwo", "valueTwo");
firstMap.put("THIS KEY WILL BE REMOVED", "valueThree");
System.out.println("\nMAP ONE\n" + firstMap + "\n");
secondMap.put("keyOne", "valueOne");
secondMap.put("keyTwo", "valueTwo");
System.out.println("\nMAP TWO\n" + secondMap + "\n");
// Remove everything from firstMap that is in secondMap.
firstMap.keySet().removeAll(secondMap.keySet());
System.out.println("\nMAP ONE MATCHING MAP TWO?\n" + firstMap + "\n");
See the JavaDoc for Map.keySet():
Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. ... The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations....
You don't need to iterate over the maps.
You can simply do
firstMap.keySet().removeAll(secondMap.keySet());
This will remove all keys from the first map that are present in the second map.
Also, you can remove all keys in the first map that are not in the second map using:
firstMap.keySet().retainAll(secondMap.keySet());
You are not using the iterator correctly. You only advance the iterator once (firstMapIterator.next()), so the first key obtained by the iterator will be the one removed from the Map, regardless of the current key in the for(String key : firstMap.keySet()) loop.
You don't need the for loop:
Iterator<String> firstMapIterator = firstMap.keySet().iterator();
while (firstMapIterator.hasNext()) {
if(!secondMap.containsKey(firstMapIterator.next())) {
firstMapIterator.remove();
break;
}
}
As others have already said, you can do it in one single line:
firstMap.keySet().removeAll(secondMap.keySet());
Another way would be by using the Collection.removeIf method:
firstMap.keySet().removeIf(k -> secondMap.containsKey(k));
The above can be rewritten as follows:
firstMap.keySet().removeIf(secondMap::containsKey);
check your firstMapIterator.next(); add into for loop
HashMap<String, String> firstMap = new HashMap<String, String>();
HashMap<String, String> secondMap = new HashMap<String, String>();
firstMap.put("keyOne", "valueOne");
firstMap.put("keyTwo", "valueTwo");
firstMap.put("THIS KEY WILL BE REMOVED", "valueThree");
System.out.println("\nMAP ONE\n" + firstMap + "\n");
secondMap.put("keyOne", "valueOne");
secondMap.put("keyTwo", "valueTwo");
System.out.println("\nMAP TWO\n" + secondMap + "\n");
Iterator<String> firstMapIterator = firstMap.keySet().iterator();
if(!firstMap.equals(secondMap)){
for(String key : firstMap.keySet()){
firstMapIterator.next();//add here in for loop
if(firstMap.containsKey(key) && !secondMap.containsKey(key)){
firstMapIterator.remove();
break;
}
}
}
System.out.println("\nMAP ONE MATCHING MAP TWO?\n" + firstMap + "\n");

How can I iterate over the results of a hash map where the value is a list?

I've created a hash map that groups unique keys that combine three parameters, i.e. customer, sc and admin. I want to create a unique list of keys with a list of servers attached. I've implemented the following:
public static void main(String[] args) {
String items = "customer1^sc1^admin1|server1~" +
"customer1^sc1^admin1|server2~" +
"customer1^sc1^admin1|server3~" +
"customer2^sc1^admin1|server1~" +
"customer3^sc1^admin1|server3~" +
"customer3^sc1^admin1|server2~";
// Set up raw data
List<String> splitItems = Arrays.asList(items.split("\\s*~\\s*"));
// Display raw data
System.out.println("Raw List: " + items);
// Create a hash map containing customer name as key and list of logs as value
HashMap<String, List<String>> customerHashMap = new HashMap<>();
// Loop through raw data
for (String item : splitItems) {
// Create new lists. One for customers and one for logs
// List<String> customerList = new ArrayList<>();
List<String> logList;
String list[] = item.split("\\|");
String customer = list[0];
String log = list[1];
logList = customerHashMap.get(customer);
if (logList == null){
logList = new ArrayList<>();
customerHashMap.put(customer, logList);
}
logList.add(log);
// System.out.println(logList);
}
// Print out of the final hash map. Customer "a" should only have "a" logs, customer "b" with "b", etc.
System.out.println("");
List<String> hashMapList = new ArrayList<String>();
Iterator it = customerHashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
String output = pair.getKey() + "|" + pair.getValue().toString();
hashMapList.add(output);
it.remove();
}
String hashMapResultString = hashMapList.toString();
String hashMapResultFormatted = hashMapResultString.replaceAll("[\\[\\]]", "");
System.out.println(hashMapResultFormatted);
}
Raw List: customer1^sc1^admin1|server1~customer1^sc1^admin1|server2~customer1^sc1^admin1|server3~customer2^sc1^admin1|server1~customer3^sc1^admin1|server3~customer3^sc1^admin1|server2~
Hash Map String:
customer2^sc1^admin1|server1, customer3^sc1^admin1|server3, server2, customer1^sc1^admin1|server1, server2, server3
I now want to use the hash map to create a string which will be parsed further (don't ask lol). So I set the keys and values of the hash map to a string which separates them with a unique delimiter |. The problem is that because the key is a List<String>, when printing I can't ascertain the beginning of every new key if its value is a list with more than one item, i.e. customer3^sc1^admin1|server3, server2, is followed immediately by customer1^sc1^admin1|server1, server2, server3. I need a delimiter here that separates them.
My ideal output would look like this:
customer2^sc1^admin1|server1~customer3^sc1^admin1|server3, server2~customer1^sc1^admin1|server1, server2, server3~...
How can I achieve this?
Update:
This is the answer I ultimately found useful for my particular problem:
StringBuilder s = new StringBuilder();
for (Map.Entry<String, List<String>> entry : customerHashMap.entrySet()) {
s.append(entry.getKey() + "|");
List<String> list = entry.getValue();
for (String item : list) {
if (item != list.get(list.size() - 1)) {
s.append(item + "^");
} else {
s.append(item);
}
}
s.append("~");
}
System.out.println(s.toString());
You can iterate through a map's entry set:
StringBuilder s = new StringBuilder();
for(Map.Entry<String,List<String>> entry : map.entrySet()) {
s.append(entry.getKey() + "\n");
List<String> list = entry.getValue();
for(String item : list) {
s.append(" " + item + "\n");
}
}
return s.toString();
For the sake of a clearer example, I've output a different format from the one you asked for, but this illustrates how to work with a map of list values. When adapting to your needs, have a look at java.util.StringJoiner and the related Collectors.joining(); it may well be useful.
Streams can be handy here:
String encoded = map.entrySet().stream()
.map( entry -> entry.getValue().stream()
.collect(Collectors.joining("^"))
+ "|" + entry.getKey())
.collect(Collectors.joining("~"));
What happens here is:
We get a stream of Entry<String,List<String> out of the map
The lambda entry -> ... converts each entry into a string of the form val1^v2^v3^...^valN|key, i.e. we are mapping a Stream<Entry<>> into a Stream<String>.
the final collect() joins the stream of strings into a single string using ~ as a delimiter.

how to insert multiple values of an attribute into mongoDB using java with Map?

I am writing a java code to insert form values into mongoDB using java code. I am using map to retrieve all the values from the map and inserting it into mongoDB. However, if an attribute is having multiple values, it is only inserting only one value. My code is:
Map<String, String[]> articleData = request.getParameterMap();
for(String key : articleData.keySet())
{
for(int i=0; i<articleData.get(key).length;i++)
{
document.put(key,articleData.get(key)[i]);
}
}
table.insert(document);
However, right now, it is overriding the values of the attribute having multiple values.
How can I resolve it?
Try this, It will give you a basic idea. Adjust code according to your program:
Map<String, String[]> articleData = request.getParameterMap();
for(String key : articleData.keySet())
{
BasicDBObject data =new BasicDBObject();
for(int i=0; i<articleData.get(key).length;i++)
{
data.put("",articleData.get(key)[i]);
}
document.put(key,data);
}
table.insert(document);
Encode a JSON object .
Try this out.
Map<String, String[]> articleData = request.getParameterMap();
for(String key : articleData.keySet())
{
JSONObject out = new JSONObject();
out.put("key", key);
out.put("value", articleData.get(key));
System.out.println(out);
}
dbobj.put("multiple",out);
collection.insert(dbobj);

Categories

Resources