Search code examples
javaarraylistcollectionsobjectmapper

Process array list from map


We are trying to access the array of object that placed inside a map.

Can any one guide us to get length of the array as well as fetching each element from the list. Sample map object given bellow.

{
    storeId = 1,
    ShipToStreetLine1 = test 123,
    ShipToCity = Seattle,
    OrderDetails = [{
        distributor_name = SS,
        product_name = HORN 80897 AM GUN 300BO 125 HP 50/10
    }]
}

We need to get the size of orderDetails array and if data present, then I want to fetch product_name.


Solution

  • You can try this:

    Create a POJO which is type of what you are getting in orderDetails

    Like

    public class OrderDetailElement{
        private String distributor_name;
        private String product_name;
        public String getDistributor_name() {
            return distributor_name;
        }
        public void setDistributor_name(String distributor_name) {
            this.distributor_name = distributor_name;
        }
        public String getProduct_name() {
            return product_name;
        }
        public void setProduct_name(String product_name) {
            this.product_name = product_name;
        }
    
    }
    

    in your logic class you can do is

        ArrayList<OrderDetailElement> orderDetails = yourMap.get("OrderDetails");
        List<String> products = new ArrayList<String>();
        if (orderDetails.size() > 0) {
            for (OrderDetailElement orderDetailElement : orderDetails) {
                products.add(orderDetailElement.getProduct_name());
            }
        }