List<Map<String, Object>> pcList = null;
Map<String, Object> pcMap = new HashMap<String, Object>();
ComputerConfigurations tempPC = null;
if (historyList != null) {
Iterator<ComputerConfigurations> iterator = historyList.iterator();
while (iterator.hasNext()) {
tempPC = (ComputerConfigurations) iterator.next();
pcMap.put(tempPC.getEnvironment(), tempPC);
pcList.add((Map<String, Object>) pcMap);
}
}
I am getting null pointer exception on pcList.add((Map<String, Object>)pcMap); line. [Servlet Error]-: java.lang.NullPointerException . Any suggestion ?
In Java, collections won't magically spring into existence just by adding something to them. You have to initialize pcList by creating an empty collection first:
List<Map<String, Object>> pcList = new ArrayList<>();
An empty collection isn't the same as null. An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.
Note that an object can't be of type List, because that's an interface; therefore, you have to tell Java what kind of List you really want (such as an ArrayList, as I've shown above, or a LinkedList, or some other class that implements List).
You're not initialising pcList at any point. Try this:
final List<Map<String, Object>> pcList = new LinkedList<>();
Map<String, Object> pcMap = new HashMap<String, Object>();
ComputerConfigurations tempPC = null;
if (historyList != null) {
Iterator<ComputerConfigurations> iterator = historyList.iterator();
while (iterator.hasNext()) {
tempPC = (ComputerConfigurations) iterator.next();
pcMap.put(tempPC.getEnvironment(), tempPC);
pcList.add((Map<String, Object>) pcMap);
}
}
Here is an example based answer. In this example below pcList is just initialized and is pointed to null(java do this for you, if it's a static or class member) since there are no empty list or values assigned to it.
List<Map<String, Object>> pcList;
Right now, pcList is assigned a new empty ArrayList. It does not have any values yet, but all positions in the list are empty and this pcList with the datatype ArrayList is pointed towards this new empty ArrayList.
List<Map<String, Object>> pcList = new ArrayList<>();
If an Object reference has been declared but not instantiated, its value is null.
List<Map<String, Object>> pcList = new ArrayList<Map<String, Object>>();
Map<String, Object> pcMap = new HashMap<String, Object>();
ComputerConfigurations tempPC = null;
if (historyList != null) {
Iterator<ComputerConfigurations> iterator = historyList.iterator();
while (iterator.hasNext()) {
tempPC = (ComputerConfigurations) iterator.next();
pcMap.put(tempPC.getEnvironment(), tempPC);
pcList.add((Map<String, Object>) pcMap);
}
}
Related
Given the following situation:
Map<String, Object> map1 = new HashMap();
Map<String, String> map2 = new HashMap();
map2.put("Grp A", "a");
map2.put("Grp B", "b");
map1.put("Grp",map2);
How can get the "Grp A" value from map1 ?
Change map1 to:
Map<String, Map<String, String>> map1 = new HashMap<>();
Then map1.get("Grp").get("Grp A") will work.
Of course, in general it would be safer to store map1.get("Grp") in a variable, and check if it's not null before calling the second get():
String value = null;
Map<String, String> inner = map1.get("Grp");
if (inner != null) {
value = inner.get("Grp A");
}
If you must keep map1 as Map<String, Object> (for example, if you must store values of different types in it), you'll have to check the type of the value you got from the outer Map, and cast it to a Map before obtaining the inner value:
String value = null;
Object innerObj = map1.get("Grp");
if (innerObj instanceof Map<?,?>) {
Map<?,?> inner = (Map<?,?>) map1.get("Grp");
Object obj = inner.get("Grp A");
if (obj instanceof String) {
value = (String) obj;
}
}
Simply retrieve map2 from map1 by casting to a Map and then get the desired value from that Map:
return ((Map<String,String>)map1.get("Grp")).get("Grp A");
However, better practice would be to check that map2 isn't null before retrieving "Grp A":
Map<String,String> map = (Map<String,String>)map1.get("Grp");
if (map != null) {
return map.get("Grp A");
}
#Eran's answer would be better practice, but OP asked how to retrieve the value from the given HashMap.
Since you defined map1 as Map<String, Object> it's values are returned as objects.
You can solve this by either by .
Casting .
Map<String,String> map2 = = (Map<String,String>)map1.get("Gep")
Using the right generics for m1 .
Map<String, Map<String, String>> map1 = new HashMap<>();
Below is the solution for the above problem
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<String, String> map2 = new HashMap<>();
Map<String, Map<String, String>> map1 = new HashMap<>();
map2.put("Grp A", "a");
map2.put("Grp B", "b");
map1.put("Grp",map2);
System.out.println(map1.get("Grp").get("Grp A"));
}
}
Hope this will work
Thanks...
this is my code for detail description.
i get size of Hashmapis ok. but when i try to get ArrayList<Map<String, Object>>> using key, all the ArryList have size 1.
private ArrayList<Map<String, Object>> settingInObject;
private ArrayList<Map<String, Object>> parentItemList;
private HashMap<String, ArrayList<Map<String, Object>>> childItemList;
settingInObject = new ArrayList<>();
parentItemList = new ArrayList<>();
childItemList = new HashMap<String, ArrayList<Map<String,Object>>>();
ArrayList<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
for (Map<String, Object> objectMap : settingInObject) {
if (objectMap.get("IsCheked").toString().equals("1")) {
if (arrayList.size() > 0) {
childItemList.put(parentItemList.get(parentItemList.size()).get("TitleDesc").toString().trim(), arrayList);
arrayList.clear();
}
parentItemList.add(objectMap);
} else {
arrayList.add(objectMap);
}
}
is there i do something wrong??
You are calling
arrayList.clear();
while under arayList you have still reference to added object - in result you are clearing the list that is already put in the map
If you want to have new empty list in arrayList you need to reinstance it rather
arrayList = new ArrayList<Map<String, Object>>();
I currently have a Map that is configured as such.
Map<String, ArrayList<Object>> map = new HashMap<String, ArrayList<Object>>();
where the purpose is to be able to have a setup much like the following:
array("foo"->array(1->"aaa",2->"bbb",3->"ccc"),
"bar"->array(1->"aaa",2->"bbb",3->"ccc"),
"bah"->array(1->"aaa",2->"bbb",3->"ccc"),
)
The problem I'm running into is that I can create the root array fine, but it will do the following, using the previous example as illustration
array("foo"->array(3->"ccc"),
"bar"->array(2->"bbb"),
"bah"->array(3->"ccc"),
)
What I'm trying to find out is how I can append the sub array as opposed to having it overwritten. I assume it's easily done I'm just missing something obvious.
What you need is to first check if map has an entry for a particular key. If not, then add an empty arraylist.
After that, get that arraylist from map and add object to that arraylist.
Map<String, ArrayList<Object>> map = new HashMap<String, ArrayList<Object>>();
String first = "FIRST";
if (map.get(first) == null){
map.put(first, new ArrayList<Object>());
}
map.get(first).add(new Object());
If you will print above map, you will get desired output.
Appending to Array's in Java is not possible because they have a fixed length. I suggest you use ArrayList instead.
HashMap<String, ArrayList<Object>> map = new HashMap<String, ArrayList<Object>>();
public void appendToMap(String key, Object o)
{
if(!map.containsKey(key))
{
map.put(key, new ArrayList<Object>());
}
map.get(key).add(o);
}
Afterwards just set your values:
appendToMap("foo", "aaa");
appendToMap("foo", "bbb");
// and so on...
You can just create a method to add to the sub-array, and create it if it doesn't exists :
Map<String, ArrayList<Object>> map = new HashMap<String, ArrayList<Object>>();
addToArray(map, "foo", "aaa");
addToArray(map, "foo", "bbb");
addToArray(map, "foo", "ccc");
addToArray(map, "bar", "aaa");
// ...
And the method would be :
private static void addToArray(final Map<String, ArrayList<Object>> map, final String key, final Object object) {
if (!map.containsKey(key))
map.put(key, new ArrayList<Object>());
map.get(key).add(object);
}
If you only need to store Strings in you array, you can use an ArrayList<String> instead of your ArrayList<Object>.
Switch to String instead of Object (if the list would always contain strings)
Map<String, List<String>> map = new HashMap<String, List<String>>();
Then add to your Map as follows
// check if a List already exists
if ((list = map.get("foo")) == null) { // if !exists,
list = new ArrayList<String>(1); // CREATE a new List
list.add("aaa");
map.put("foo", list); // ADD the new List to Map
} else { // if exists,
list.add("aaa"); // ADD to the existing List
}
I am trying to get data out of a list,but facing some issue while getting the data.
List<Field> errorFieldList;
Set<String> formValidationResult = new HashSet<String>();
Here the data added to validationResults is like and errorFieldList size is two having Id and type
validationResults.put(errorFieldList, formValidationResult);
public ValidationResponseErrorView(
Map<Object, Set<String>> validationResults, String exceptionMessage) {
if (validationResults.size() > 0) {
for (Map.Entry<Object, Set<String>> entrySet : validationResults
.entrySet()) {
Map<String, Object> fieldResultsMap = new HashMap<String, Object>();
Object objField = entrySet.getKey();
if (objField instanceof List) {
for (int i = 0; i < ((List<Map<String, Object>>) objField)
.size(); i++) {
LOGGER.info("in array list----" + objField);
}
}
}
}
}
I am not sure how to get data out of objField.
Your code is really hard to read and contains a lot of inconsistencies. Especially in your constructor you declare validationResults as
Map<Object, Set<String>> validationResults
But in your introduction you declare it as
List<Field> errorFieldList;
Set<String> formValidationResult = new HashSet<String>();
validationResults.put(errorFieldList, formValidationResult);
which means your Object is a List<Field>. So now you can simply use:
objField.get(i);
to retrieve the values, where i is your index you iterate over. HOWEVER: your code probably won't compile, since you try to cast the List<Field> to List<Map<String, Object>> in the 2nd for loop.
Simply put: rework the code, A Map has getter methods for the key and over a Set you need to iterate. Check first what data structure you need. Don't nest too deep.
List< Map< String, Object>> objField would return you a List which has elements of type Map<String, Object>. To get value from this use:
Map<String,Object> mapOut = ((List<Map<String, Object>>) objField).get(i);
Set<String> keySet = mapOut.keySet();
Iterator<String> itr = keySet.iterator();
while(itr.hasNext()){
Object outObject = mapOut.get(itr.next());
LOGGER.info("Object"+ outObject);
}
If I have a type
ArrayList<HashMap<String,String>> keys = functionWhichReturnsThisType();
How can I iterate through so that I end up with all <1st string of hashmap> in a string array and likewise <2nd string of hashmap> into another string array.
I have tried to use the iterator but the hierarchy in the data type is confusing me.
appPrefs = new AppPreferences(context.getApplicationContext());
ArrayList<HashMap<String,String>> keys = appPrefs.getDownloadUrls();
ArrayList<String> urls = new ArrayList<String>();
ArrayList<String> filenames = new ArrayList<String>();
Iterator myIterator = keys.keySet().iterator();
while(myIterator.hasNext()) {
urls.add((String)myIterator.next());
filenames.add((String)keys.get(myIterator.next()));
}
If the order doesn't matter, you can try
for (HashMap<String, String> map : keys) {
urls.addAll(map.keys());
filenames.addAll(map.values());
}
If you want to keep the order, you can try
for (HashMap<String, String> map : keys) {
for (Map.Entry<String, String> entry : map.entrySet()) {
urls.add(entry.getKey());
filenames.add(entry.getValue());
}
}
OK, I'll walk through your sample code and show where you're running into issues, and suggest how you can get it to work.
ArrayList<HashMap<String,String>> keys = appPrefs.getDownloadUrls();
This (above) is fine - but remember keys is an ArrayList. It's a list of HashMap objects, but it's still a list
ArrayList<String> urls = new ArrayList<String>();
ArrayList<String> filenames = new ArrayList<String>();
These are good, but in typical Java, it would be better to have List<String> urls = new ArrayList<String>(); to try and keep your variables using interfaces instead of concrete implementations.
Iterator myIterator = keys.keySet().iterator();
while(myIterator.hasNext()) {
This won't work, because keys is an ArrayList, and a list does not have a keySet() you want to do:
Iterator<HashMap<String,String> listIterator = keys.iterator();
while(listIterator.hasNext()) {
HashMap<String,String> map = listIterator.next();
Iterator<String> myIterator = map.keySet().iterator();
while(myIterator.hasNext()) {
Or, even better would be to use the Java 1.5 for(each) loop:
for( Map<String,String> map : keys ) {
for( String url : map.keySet() ) {
--
urls.add((String)myIterator.next());
The above would work, once you get myIterator to be an iterator over the map, rather than the list.
filenames.add((String)keys.get(myIterator.next()));
But this won't for 2 reasons
Because keys is still a list.
If you call next on an iterator twice then you get 2 different objects.
You need to have:
String url = myIterator.next();
urls.add(url);
filenames.add(map.get(url));
Or, if you use the for(each) loop I suggested above, then you can skip that first line.
Hope that helps - if something's unclear please add a comment.
Note: solilo's solution is a lot simpler and is a good way to do it, my answer is here to help you see where you were running into trouble.
This method will work for you extract first and second strings
private void getFirstAndSecondStrings(ArrayList<HashMap<String,String>> keys){
ArrayList<String> firstStrings = new ArrayList<String>();
ArrayList<String> secondStrings = new ArrayList<String>();
for (HashMap<String, String> map : keys) {
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pairs = (Map.Entry)iterator.next();
firstStrings.add((String)pairs.getValue());
secondStrings.add((String)pairs.getKey());
}
}
}