'In Android how can i group array item by date?

The array of objects


    Statement:[
       {
       "date": "12-09-19 11:02:47",
       "Country": "Bangladesh",
       "Profession": "X",
       "Salary": "100",
       },
       {
       "date": "12-09-19 11:02:47",
       "Country": "Bangladesh",
       "Profession": "Y",
       "Salary": "101",
       },
       {
       "date": "12-09-19 11:02:47",
       "Country": "Bangladesh",
       "Profession": "Z",
       "Salary": "102",
       },
       {
       "date": "11-09-19 11:02:47",
       "Country": "India",
       "Profession": "I",
       "Salary": "103",
       },
       {
       "date": "11-09-19 11:02:47",
       "Country": "India",
       "Profession": "J",
       "Salary": "104",
       },
       {
       "date": "10-09-19 11:02:47",
       "Country": "Nepal",
       "Profession": "N",
       "Salary": "105",
       },
       {
       "date": "10-09-19 11:02:47",
       "Country": "Nepal",
       "Profession": "M",
       "Salary": "106",
       }
       ]

I am trying to create a new array, that would create an object with each date(as a key) and other information in the same object.

The new array should look like:

    "10-09-19": [
    {
      "Country": "Nepal",
      "Profession": "M",
      "Salary": "106",
    },
    {
      "Country": "Nepal",
      "Profession": "N",
      "Salary": "105",
    }
    ],
    "11-09-19": [{
      "Country": "India",
      "Profession": "J",
       "Salary": "104",
    },
    {
      "Country": "India",
      "Profession": "I",
      "Salary": "103",
    }
    ],
    "12-09-19": [{
      "Country": "Bangladesh",
      "Profession": "x",
       "Salary": "104",
    },
    {
      "Country": "Bangladesh",
      "Profession": "y",
      "Salary": "103",
    },
    {
      "Country": "Bangladesh",
      "Profession": "z",
      "Salary": "102",
    }
    ]





Solution 1:[1]

I assume that what you provided are both JSON string (but they look not valid), then you can achieve the conversion as follows:

ObjectMapper mapper = new ObjectMapper();
ObjectNode root = (ObjectNode) mapper.readTree(jsonStr);
ObjectNode rootNew = mapper.createObjectNode();
for (int i = 0; i < root.get("Statement").size(); i++) {
    String date = root.get("Statement").get(i).get("date").asText().split(" ")[0];
    ObjectNode node = (ObjectNode) ((ObjectNode) root.get("Statement").get(i));
    node.remove("date");
    if (rootNew.has(date)) {
        ((ArrayNode) rootNew.get(date)).add(node);
    } else {
        rootNew.put(date, mapper.createArrayNode().add(node));
    }
}
System.out.println(rootNew.toString());

Console output:

{
  "12-09-19":[
    {
      "Country":"Bangladesh",
      "Profession":"X",
      "Salary":"100"
    },
    {
      "Country":"Bangladesh",
      "Profession":"Y",
      "Salary":"101"
    },
    {
      "Country":"Bangladesh",
      "Profession":"Z",
      "Salary":"102"
    }
  ],
  "11-09-19":[
    {
      "Country":"India",
      "Profession":"I",
      "Salary":"103"
    },
    {
      "Country":"India",
      "Profession":"J",
      "Salary":"104"
    }
  ],
  "10-09-19":[
    {
      "Country":"Nepal",
      "Profession":"N",
      "Salary":"105"
    },
    {
      "Country":"Nepal",
      "Profession":"M",
      "Salary":"106"
    }
  ]
}

Solution 2:[2]

Use hashmap to store data date wise. Key of hashmap will be the date . here is my code it might help you to understand the logic.

      var sortedList= HashMap<String, MutableList<Model>>() // create hashmap to store data
        var temp: MutableList<Model>? = ArrayList<Model>()
        for (item in currentList!!) {
            temp = sortedList?.get(item.date.split(" ").get(0)) // get date and remove timing

            if (temp != null)     //if this is not null it mean this contain items
                temp.add(item)
            else {
                temp = ArrayList<Model>()  //if this is null it means this is new data or new data
                temp.add(item)
            }

            sortedList?.put(item.date.split(" ").get(0), temp)
    }

My code is in kotlin sorry for that. Happy coding.

Solution 3:[3]

You can use Java 8 group by. Hope below code will help you

Map<String, List<Pojo>> groupedList = 
list.stream().collect(Collectors.groupingBy(Pojo::getDate, Collectors.toList()));

Solution 4:[4]

First of all thank you guys for answering my question. I have a solution which i found later. I think i should share that with you guys.

JSONArray statementArray = response.getJSONArray("statement");

Map<String, List<String>> map= new HashMap<String, List<String>>();
for(int i = 0; i < statementArray.length(); i ++) {

   JSONObject mJsonObjectStatement = statementArray.getJSONObject(i);
   String date= mJsonObjectStatement.getString("date").split(" ")[0];
   List<String> valSet = new ArrayList<String>();
   valSet.add(0,mJsonObjectStatement.getString("Country"));
   valSet.add(1,mJsonObjectStatement.getString("Profession"));
   valSet.add(2,mJsonObjectStatement.getString("Salary"));
   map.put(date,valSet);
}
for (Map.Entry<String, List<String>> entry : transactionReportMap.entrySet()) {
   String key = entry.getKey();
   List<String> values = entry.getValue();
   Log.e("Key = " , key);
   Log.e("Values = " , values + "n");
}
Log.e("Result:",map.toString());

The above solution is not provide the same result but it serve my purpose.

Another solution i found

JSONArray statementArray = response.getJSONArray("statement");

ObjectMapper mapper = new ObjectMapper();
Map<String, List<String>> map= new HashMap<String, List<String>>();
for(int i = 0; i < statementArray.length(); i ++) {
   JSONObject mJsonObjectStatement = statementArray.getJSONObject(i);
   String date= mJsonObjectStatement.getString("date").split(" ")[0];
   if (transactionReportMap.containsKey(date)) {
       map.get(date).add(date);
   } else {
       ArrayList<String> infoList = new ArrayList<String>();
       infoList.add(mJsonObjectStatement.getString("Country"));
       infoList.add(mJsonObjectStatement.getString("Profession"));
       infoList.add(mJsonObjectStatement.getString("Salary"));
       map.put(date, infoList);
   }
}
StringWriter result = new StringWriter();
try {
  mapper.writeValue(result, map);
} catch (IOException e) {
  e.printStackTrace();
}
Log.e("Result: ",result+"");

Solution 5:[5]

This might be too late for this question, but I am sharing my answer.

            //Define an empty hash map
            Map<String, JSONObject> finalMap = map;

            for (JSONObject object : Statement) {
                String key = object.getString("date");

                //Split the date from date time
                if (key.contains(" ")) {
                    key = key.split(" ")[0];
                }

                if (finalMap.containsKey(key)) {
                    JSONArray list = finalMap.get(key);
                    list.put(student);

                } else {
                    JSONArray list = new JSONArray();
                    list.put(object);

                    finalMap.put(key, list);
                }
            }

Finally you can convert the hash map in to any type you need.

Solution 6:[6]

Start by looping the array to get the date. Create a JSONArray of the date as shown below.

JSONArray jsonArray = new JSONArray("date");

//loop through the array while adding the objects u need

for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObj = jsonArray.getJSONObject(i);
jsonObj.put("item1", value1);
jsonObj.put("item2", value2);


jsonArray.put(jsonObj);

} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LHCHIN
Solution 2 Rahul sharma
Solution 3 Farhan Sheharyar
Solution 4 Saymum Sany
Solution 5 Waseem
Solution 6 simon