Search code examples
javaarrayshashmapjava-ee-6

Looping array of only two object to assign to the Map?


I was trying to work on an example to loop the array of objects which are only just two objects, and getting the values to assign it to the map by the setting key and the values fetched from the array object. How can i differentiate the object 1 and object 2 from the array to go in the map1 and map2 object? I want the values of array with index 0 object to in map1 and the other array with index 1 in the other map.

Map<String,String> map1 = new HashMap<String,String>();
Map<String,String> map2 = new HashMap<String,String>();

for(MyArray obj : actualArray){

//how can i the object 1 and object 2 from the array and assign it to the map1 for object1 values and map2 for object2 values.??

}

I was trying below way instead of looping which is throwing arrayOutOfBoundException if any of the either objects is not available;

map1.put("firstName", myArray[0].getFirstName());
map1.put("firstName", myArray[0].getLasttName());

map2.put("firstName", myArray[1].getFirstName());
map2.put("firstName", myArray[1].getLasttName());

I tried to find some solutions and examples online but no luck, any suggestions and help will be appreciated as am new in java programming.


Solution

  • Probably this snippet would help. As suggested by Guest01, you should consider creating a list of map to easily do the assignments.

        List<Map<String, String>> mapList = new ArrayList<>();
        if (myObjects != null && myObjects.length > 0) {
            for (myObject myObject : myObjects) {
                Map<String, String> mapItem = new HashMap<>();
                if (myObject != null /*&& Other Checks on FirstName and LastName*/) {
                    mapItem.put("firstName", myObject.getFirstName());
                    mapItem.put("lastName", myObject.getLastName());
                    mapList.add(mapItem);
                }
            }
        }