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());
}
}
Related
I use SimpleExpandableListAdapter to create ExpandableListView for my application. I want to know better how to work with lists and maps and what they are in practice.
//collection for elements of a single group;
ArrayList<Map<String, String>> childDataItem;
//general collection for collections of elements
ArrayList<ArrayList<Map<String, String>>> childData;
Map<String, String> m;
I know how to iterate over ArrayList of Maps, it is not a problem for me, but I got stuck.
childData = new ArrayList<>();
childDataItem = new ArrayList<>();
for (String phone : phonesHTC) {
m = new HashMap<>();
m.put("phoneName", phone);
childDataItem.add(m);
}
childData.add(childDataItem);
childDataItem = new ArrayList<>();
for (String phone : phonesSams) {
m = new HashMap<String, String>();
m.put("phoneName", phone);
childDataItem.add(m);
}
childData.add(childDataItem);
// создаем коллекцию элементов для третьей группы
childDataItem = new ArrayList<>();
for (String phone : phonesLG) {
m = new HashMap<String, String>();
m.put("phoneName", phone);
childDataItem.add(m);
}
childData.add(childDataItem);
And I want to Log what childData contains (<ArrayList<Map<String, String>>), but I don't sure that I did that right. ( 2nd loop is a simple ArrayList of Map iteration)
for (ArrayList<Map<String, String>> outerEntry : childData) {
for(Map<String, String> i:outerEntry ) {
for (String key1 : i.keySet()) {
String value1 = i.get(key1);
Log.d("MyLogs", "(childData)value1 = " + value1);
Log.d("MyLogs", "(childData)key = " + key1);
}
}
for (Map<String, String> innerEntry : childDataItem) {
for (String key : innerEntry.keySet()) {
String value = innerEntry.get(key);
Log.d("MyLogs", "(childDataItem)key = " + key);
Log.d("MyLogs", "(childDataItem)value = " + value);
}
}
}
If you want to log all the elements for childData then there is no need for the last loop, you are already fetching them in the first loop. Please remove below code from the program and it will log all items of childData.
for (Map<String, String> innerEntry : childDataItem) {
for (String key : innerEntry.keySet()) {
String value = innerEntry.get(key);
Log.d("MyLogs", "(childDataItem)key = " + key);
Log.d("MyLogs", "(childDataItem)value = " + value);
}
}
Above loop is iterating over childDataItem and you are using the same reference again and again in your code so in this case above loop will contain only most recent map items.
For simplicity, I changed your log statements to sysout and here's the example and output:
ArrayList<Map<String, String>> childDataItem;
//general collection for collections of elements
ArrayList<ArrayList<Map<String, String>>> childData;
Map<String, String> m;
childData = new ArrayList<>();
childDataItem = new ArrayList<>();
m = new HashMap<>();
m.put("phoneName", "HTC");
m.put("phoneName1", "HTC1");
childDataItem.add(m);
childData.add(childDataItem);
childDataItem = new ArrayList<>();
m = new HashMap<String, String>();
m.put("phoneName", "Samsung");
childDataItem.add(m);
childData.add(childDataItem);
// создаем коллекцию элементов для третьей группы
childDataItem = new ArrayList<>();
m = new HashMap<String, String>();
m.put("phoneName", "LG");
childDataItem.add(m);
childData.add(childDataItem);
for (ArrayList<Map<String, String>> outerEntry : childData) {
for(Map<String, String> i:outerEntry ) {
for (String key1 : i.keySet()) {
String value1 = i.get(key1);
System.out.println("MyLogs (childData)value1 = " + value1);
System.out.println("MyLogs (childData)key = " + key1);
}
}
}
Output
MyLogs (childData)value1 = HTC1
MyLogs (childData)key = phoneName1
MyLogs (childData)value1 = HTC
MyLogs (childData)key = phoneName
MyLogs (childData)value1 = Samsung
MyLogs (childData)key = phoneName
MyLogs (childData)value1 = LG
MyLogs (childData)key = phoneName
So as you probably know, an array list is just a sequential store of data objects. And a map is a key-value pair mapping where the key is used as the lookup and must be unique. That is to say in a Map you may have many duplicate values but only one key.
As for iterating over a Map you can use an entry set which makes it a little easier. So if you wanted to iterate over an object of type <ArrayList<Map<String, String>> it would look something like this for your childDataItem class.
for(Map<String, String> map : childDataItem){
//Take each map we have in the list and iterate over the keys + values
for(Map.Entry<String, String> entry : map){
String key = entry.getKey(), value = entry.getValue();
}
}
And in your other case, the example is the same except you have another layer of array list.
for(List<Map<String, String>> childDataItemList : childData){
for(Map<String, String> map : childDataItemList){
//Take each map we have in the list and iterate over the keys + values
for(Map.Entry<String, String> entry : map){
String key = entry.getKey(), value = entry.getValue();
}
}
}
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.
I have a hashmap which contains student id as key and some string as value.
It contains data like
a abc.txt
b cde.txt
d abc.txt
I want to find the duplicate values in map and replace them with genreic values. I want a map like
a abc.txt
b cde.txt
d abc_replacevalue.txt
I have tried with the code but its not working
Map<String,String> filemap = new HashMap<String,String>();
// filemap is the original hash map..
Set<String> seenValues = new HashSet<String>();
Map<String, String> result = new HashMap<String, String>();
for (Map.Entry<String, String> entry : filemap.entrySet()) {
String value = entry.getValue();
if (seenValues.contains(value)) {
value = "updated"; // update value here
}
result.put(entry.getKey(), value);
seenValues.add(value);
}
for (String key : result.keySet() ) {
String value = result.get( key );
System.out.println(key + " = " + value);
}
The output is still the same
a abc.txt
b cde.txt
d abc.txt
You can generate a new map from an existing one, checking every new value that you come across to see if it has already been seen:
Set<String> seenValues = new HashSet<String>();
Map<String, String> result = new HashMap<String, String>();
for (Map.Entry<String, String> entry : original.entrySet()) {
String value = entry.getValue();
if (seenValues.contains(value)) {
value = ...; // update value here
}
result.put(entry.getKey(), value);
seenValues.add(value);
}
All,
I have a map with categories and subcategories as lists like this:
Map<String,List<String>> cat = new HashMap<String,List<String>>();
List<String> fruit = new ArrayList<String>();
fruit.add("Apple");
fruit.add("Pear");
fruit.add("Banana");
cat.put("Fruits", fruit);
List<String> vegetable = new ArrayList<String>();
vegetable.add("Carrot");
vegetable.add("Leak");
vegetable.add("Parsnip");
cat.put("Vegetables", vegetable);
I want to find if "Carrot" is in the map and to which key ("Fruit') it matches, however:
if (cat.containsValue("Carrot")) {System.out.println("Cat contains Leak");}
gives False as outcome. How can I match "Carrot" and get back the key value "Vegetable"
Thx.
You need to create the inversed map:
Map<String, String> fruitCategoryMap = new HashMap<>();
for(Entry<String, List<String>> catEntry : cat.entrySet()) {
for(String fruit : catEntry.getValue()) {
fruitCategoryMap.put(fruit, catEntry.getKey());
}
}
Then you can simply do:
String category = fruitCategoryMap.get("Banana"); // "Fruit"
Iterate thought all the keys and check in the value if found then break the loop.
for (String key : cat.keySet()) {
if (cat.get(key).contains("Carrot")) {
System.out.println(key + " contains Carrot");
break;
}
}
You have to search for the value in the entire map:
for (Entry<String, List<String>> entry : cat.entrySet()) {
for (String s : entry.getValue()) {
if (s.equals("Carrot"))
System.out.println(entry.getKey());
}
}
try this,
for (Map.Entry<String, List<String>> entry : cat.entrySet()) {
String names[] = entry.getValue().toArray(new String[entry.getValue().size()]);
for (int i = 0; i < names.length; i++) {
if (names[i].equals("Carrot")) {
System.out.println("found"+names[i]);
break;
}
}
}
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