There are in fact a lot of questions in your question ;-)
First of all I said your json is not valid. The brackets are missing and also some commas.
I would store the data in a simple java object first. So let's create a Person class and implement our own toString-Method.
public class Person {
String name;
String email;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
String output = "Name: " + this.name + "\n";
output += "Email: " + this.email + "\n";
output += "Age: " + this.age + "\n\n";
return output;
}
}
Then you can iterate through the json array, create a Person object in each iteration and fill it with the data. Also in each iteration we will put that Person object into a map with the 'age' as key.
The result is a Map that has the age as key and a list of persons as values. You can iterate through them now (as I did here) or you can access the lists directly via the age-key.
public static void main(String[] args) {
String text = "[{\"name\": \"Ram\",\"email\": \"ram@gmail.com\",\"age\": 23}, {\"name\": \"Shyam\",\"email\": \"shyam23@gmail.com\",\"age\": 28}, {\"name\": \"John\",\"email\": \"john@gmail.com\",\"age\": 23}, {\"name\": \"Bob\",\"email\": \"bob32@gmail.com\",\"age\": 41}]";
JSONArray jsonArr = new JSONArray(text);
Map<Integer, List<Person>> ageMap = new HashMap<Integer, List<Person>>();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject obj = (JSONObject) jsonArr.get(i);
Person person = new Person();
person.setName(obj.getString("name"));
person.setEmail(obj.getString("email"));
person.setAge(obj.getInt("age"));
int age = person.getAge();
List<Person> ageList = ageMap.get(age);
if (ageList == null) {
ageList = new ArrayList<Person>();
}
ageList.add(person);
ageMap.put(age, ageList);
}
for (Map.Entry<Integer, List<Person>> entry : ageMap.entrySet()) {
List<Person> ageList = entry.getValue();
if (ageList.size() > 1) {
System.out.println("*****************************");
System.out.println("Person with same age '" + entry.getKey() + "':" + "\n");
for (Person person : ageList) {
System.out.println(person.toString());
}
System.out.println("\n");
}
}
}
Of course this is not the only way to do that and I'm sure that this can be done in a more efficient way.