Friday 2 December 2016

java - Access values of hashmap











I am having a MAP, Map map = new HashMap ();



public class Records 
{
String countryName;
long numberOfDays;


public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getNumberOfDays() {
return numberOfDays;
}

public void setNumberOfDays(long numberOfDays) {
this.numberOfDays = numberOfDays;
}

public Records(long days,String cName)
{
numberOfDays=days;
countryName=cName;
}


public Records()
{
this.countryName=countryName;
this.numberOfDays=numberOfDays;
}


I have implemented the methods for map, now please tell me How do I access all the values that are present in the hashmap. I need to show them on UI in android ?


Answer



You can use Map#entrySet method, if you want to access the keys and values parallely from your HashMap: -




Map map = new HashMap ();

//Populate HashMap

for(Map.Entry entry: map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}



Also, you can override toString method in your Record class, to get String Representation of your instances when you print them in for-each loop.



UPDATE: -



If you want to sort your Map on the basis of key in alphabetical order, you can convert your Map to TreeMap. It will automatically put entries sorted by keys: -



    Map treeMap = new TreeMap(map);

for(Map.Entry entry: treeMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());


}


For more detailed explanation, see this post: - how to sort Map values by key in Java


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...