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.
Related
I am pulling data from db and puting it into an hashmap.
HashMap<String,Object> players= new HashMap();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
players.put(childSnapshot.getKey(), childSnapshot.getValue());
}
for (Map.Entry<String, Object> entry : players.entrySet()) {
Log.d("asd","Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Log.d output is :
D/asd: Key = lastpeony, Value = {lat=40.89, long=29.37, avatar=dino}
D/asd: Key = lifesuxtr, Value = {lat=40.8901765, long=29.377306, avatar =petyr}
what i am trying to do is access lat long and avatar values for each key.
How do i do that ?
Because later i am going to use those values to draw markers on a map.
thanks
If you want to extract something specific(latti or longi) within each value of HashMap<String,Object> players map, the value type should be more specific than just Object type. So, instead of using HashMap<String,Object> to store players, use HashMap<String,SomeSpecificType>
You use hashmap .get https://developer.android.com/reference/java/util/HashMap.html#get(java.lang.Object)
String key = "lastpeon";
Object value = players.get(key);
Change
HashMap<String,Object> players= new HashMap();
to
HashMap<String,Map<String,Object>> players= new HashMap<>();
Then initialize the Map with:
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
players.put(childSnapshot.getKey(), (Map<String,Object>)childSnapshot.getValue());
}
Then you can iterate over the inner Maps:
for (Map.Entry<String, Map<String,Object>> entry : players.entrySet()) {
for (Map.Entry<String, Object> ientry : entry.getValue().entrySet()) {
Log.d("asd","Key = " + ientry.getKey() + ", Value = " + ientry.getValue());
}
}
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");
i'm moving from php to Java. and i'm trying to achieve something like below in Java :
$user = array(
"firstname" => "myname",
"lastname" => "surname",
"phone" => array(
"home" => "123213213213",
"office" => "312321321312312",
"mobile" => "4532134213131312"
)
)
is there any way to do like that in java?
Thanks!
There are are few ways to make it closer, but nothing as convenient as that.
Example 1:
Map<String, Object> user = new HashMap<String, Object>() {
{
put("firstname", "myname");
put("lastname", "surname");
put("phone", new HashMap<String, String>() {
{
put("home", "123213213213");
put("office", "312321321312312");
put("mobile", "4532134213131312");
}
});
}
};
Update example:
((Map)user.get("phone")).put("mobile2", "123");
Adding another map:
user.put("address", new HashMap<String, Object>());
(could perhaps be improved by use of putIfAbsent method, or the merge-methods)
Printing current contents:
System.out.println(user);
Gives:
{firstname=myname, address={}, phone={mobile2=123, mobile=4532134213131312, office=312321321312312, home=123213213213}, lastname=surname}
For instance you can use the following code :
Map<String, Object> map = new HashMap<>();
map.put("firstname", "myname");
Map<String, String> phones = new HashMap<>();
phones.put("home" , "123213213213");
phones.put("office" , "312321321312312");
phones.put("mobile" , "4532134213131312");
map.put("phones", phones);
You could use the JSON API in Java to create an object in the format you like. Here is the documentation of the JSON API
http://www.oracle.com/technetwork/articles/java/json-1973242.html
Example:
String stringToParse = "{" +
"firstname: \"myname\"," +
"lastname: \"surname\"," +
"phone: [ " +
" { home: \"123213213213\" }, " +
" { office: \"312321321312312\" }," +
" { mobile: \"4532134213131312\" }" +
"]" +
"}";
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
It is "possible" but I don't think it would be good convention (unless there is another way I am unaware of). I believe that this would work:
HashMap<String, Object> hm = new HashMap<String, Object>();
I would think that you would have to use a List object type instead of a array data type for a HashMap. If I were doing this, I would likely create my own class that handles this situation.
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]);
}
I have a method which is returning List<Map<String,Object>>.
How to iterate over a list like List<Map<String,Object>>?
It sounds like you're looking for something like this:
List<Map<String, Object>> list; // this is what you have already
for (Map<String, Object> map : list) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
}
}
List<Map<String, Object>> list = getMyMap();
for (Map<String, Object> map : list) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
Loop through list of maps
Handle map entries
with java 1.8 (8) you can re-write it like:
list.forEach(item ->
item.forEach((k, v) -> System.out.println(k + ": " + (String)v)
);
I'm posting you one simple Example of List<Map<String,Object>>.
public static void main(String[] args){
Map<String,Object> map1 = new HashMap<>();
map1.put("Map1 Key1", (Object) "Map1 value1");
map1.put("Map1 Key2", (Object) "Map1 value2");
Map<String,Object> map2 = new HashMap<>();
map2.put("Map2 Key1", (Object) "Map2 value1");
map2.put("Map2 Key2", (Object) "Map2 value2");
List<Map<String,Object>> list = new ArrayList<>();
list.add(map1);
list.add(map2);
list.stream().forEach(mapsData->{
mapsData.entrySet().forEach(mapData->{
System.out.println("Key:"+mapData.getKey()+ " Value:"+mapData.getValue());
});
});
}
This should work:
List<Map<String, Object>> list = ...
for (Map<String, Object> map : list)
{
...
}
You can also use an iterator or the get method within a for loop to access the elements within the List.
Map<String, String> map = new HashMap<>();
map.put("First", "1");
map.put("Second", "2");
map.put("third", "3");
map.put("four", "4");
// here is the logic
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
This is an easy way to iterate over a list of Maps as my starting point. My List had one Map object inside with 3 values
List<Map<String, Object>>
using Java's functional programming in a rather short and succinct manner. The purpose here was to pull out all the maps stored in a list and print them out. I could have also collected the values etc.
answerListOfMaps.stream().map(map -> map.entrySet())
.forEach(System.out::println );
output in Eclipse IDE console looked like this:
[isAllowed=true, isValid=true, cardNumber=672xxxxxxxxxxx]
x's for Obfuscation
alternate way:
answerListOfMaps.stream().flatMap(map -> map.entrySet().stream())
.forEach( entry -> System.out.println(entry.getKey() + ":" + entry.getValue()) );
console:
isAllowed:true
isValid:true
cardNumber:672xxxxxxxxxxx