Johan Sánchez
Johan Sánchez

Reputation: 165

Iterate ArrayList

I want to know the best way to iterate this ArrayList, this ArrayList comes from a Response from an API, this is the ArrayList: enter image description here

The problem is that i dont know how to get the "id" and the "value" from the loop, i know the arraylist size but i dont have any idea how to print the "Keys" and "Values" from this Array

        for(int i=1; i <= contacts.size(); i++) {
        //Example System.out.print(contacts[i]->id);
        //Example System.out.print(contacts[i]->contact_name) ;
        //Example System.out.print(contacts[i]->numbers);
        //Example System.out.print(contacts[i]->emails);
        //I want to print id and value
        //
    }

In onResponse i call this fucntion for example:

ServerResponse resp = response.body();
functionExample((ArrayList) resp.getResponse());

The functionExample have an ArrayList as parameter. This is my result from my resp.getResponse():

enter image description here

This is my json from the API:

{
"result": "success",
"message": "Lista de Contactos",
"response": [
    {
        "id": 1,
        "contact_name": "EDIFICADORA JUANA",
        "numbers": "{24602254,55655545}",
        "emails": "{[email protected],[email protected]}"
    },
    {
        "id": 2,
        "contact_name": "LA MEJOR",
        "numbers": "{25445877,25845877}",
        "emails": "{[email protected]}"
    }
  ]
}

I appreciate any help.

Upvotes: 2

Views: 3144

Answers (6)

Dinier Arteaga
Dinier Arteaga

Reputation: 48

  public void FunctionExample(ArrayList contacts) {

  for(int i=0; i < contacts.size(); i++) {

        LinkedTreeMap<String, Object> map = (LinkedTreeMap<String, Object>) contacts.get(i);
        map.containsKey("id");
        String id = (String) map.get("id");
        map.containsKey("contact_name");
        String contact_name = (String) map.get("contact_name");
        map.containsKey("numbers");
        String numbers = (String) map.get("numbers");
        numbers.replace("{","").replace("}","");
        map.containsKey("emails");
        String emails = (String) map.get("emails");
        emails.replace("{","").replace("}","");

        Snackbar.make(getView(), id, Snackbar.LENGTH_LONG).show();
        Snackbar.make(getView(), contact_name, Snackbar.LENGTH_LONG).show();
        Snackbar.make(getView(), numbers, Snackbar.LENGTH_LONG).show();
        Snackbar.make(getView(), emails, Snackbar.LENGTH_LONG).show(); 

  }
} 

Upvotes: 2

Anil
Anil

Reputation: 603

If you are using Set< Map< String, String>> set;

set.stream().forEach(map -> {
      System.out.print("Id:" + map.get("id") + "ContactName:" + map.get("contact_name"));
    });

Upvotes: 1

JVOneLife
JVOneLife

Reputation: 74

Try this loop to extract every value from ArrayList of yours

List<LinkedTreeMap> list = new ArrayList<LinkedTreeMap>(); //assign result from API to list
    for(LinkedTreeMap<String,String> contact : list){
        for(String id : contact.keySet()){
            if(id.equalsIgnoreCase("id")){
                System.out.println("ID: "+ contact.get(id));
            }else if(id.equalsIgnoreCase("contact_name")){
                System.out.println("Contact Name: "+ contact.get(id));
            }else{  //if it is list of numbers or e-mails
                String result = contact.get(id);
                result = result.replaceAll("{|}", ""); //removing { }
                String[] array = result.split(",");
                System.out.println(id+": "); // this will be either numbers or e-mails
                //now iterating to get each value
                for(String s : array){
                    System.out.println(s);
                }
            }
        }
    }

Upvotes: 0

Szymon Stepniak
Szymon Stepniak

Reputation: 42272

I would strongly encourage you to use e.g. Jackson to map your JSON response to a proper object. Consider following example:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JacksonTest {

    private static final String JSON = "{\n" +
            "\"result\": \"success\",\n" +
            "\"message\": \"Lista de Contactos\",\n" +
            "\"response\": [\n" +
            "    {\n" +
            "        \"id\": 1,\n" +
            "        \"contact_name\": \"EDIFICADORA JUANA\",\n" +
            "        \"numbers\": \"{24602254,55655545}\",\n" +
            "        \"emails\": \"{[email protected],[email protected]}\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"id\": 2,\n" +
            "        \"contact_name\": \"LA MEJOR\",\n" +
            "        \"numbers\": \"{25445877,25845877}\",\n" +
            "        \"emails\": \"{[email protected]}\"\n" +
            "    }\n" +
            "  ]\n" +
            "}";

    @Test
    public void testParsingJSONStringWithObjectMapper() throws IOException {
        //given:
        final ObjectMapper objectMapper = new ObjectMapper();

        //when:
        final Response response = objectMapper.readValue(JSON, Response.class);

        //then:
        assert response.getMessage().equals("Lista de Contactos");
        //and:
        assert response.getResult().equals("success");
        //and:
        assert response.getResponse().get(0).getId().equals(1);
        //and:
        assert response.getResponse().get(0).getContactName().equals("EDIFICADORA JUANA");
        //and:
        assert response.getResponse().get(0).getEmails().equals(Arrays.asList("[email protected]", "[email protected]"));
        //and:
        assert response.getResponse().get(0).getNumbers().equals(Arrays.asList(24602254, 55655545));
    }

    static class Response {
        private String result;
        private String message;
        private List<Data> response = new ArrayList<>();

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public List<Data> getResponse() {
            return response;
        }

        public void setResponse(List<Data> response) {
            this.response = response;
        }
    }

    static class Data {
        private String id;
        @JsonProperty("contact_name")
        private String contactName;
        private String numbers;
        private String emails;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getContactName() {
            return contactName;
        }

        public void setContactName(String contactName) {
            this.contactName = contactName;
        }

        public List<Integer> getNumbers() {
            return Stream.of(numbers.replaceAll("\\{", "")
                    .replaceAll("}", "")
                    .split(","))
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());
        }

        public void setNumbers(String numbers) {
            this.numbers = numbers;
        }

        public List<String> getEmails() {
            return Arrays.asList(emails.replaceAll("\\{", "")
                    .replaceAll("}", "")
                    .split(","));
        }

        public void setEmails(String emails) {
            this.emails = emails;
        }
    }
}

In this example I used same JSON response you receive and jackson-core library (http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.8.9) for mapping String to a POJOs (instead of String you can use InputStream, byte[] etc.). There are two POJOs: Response and Data. Response aggregates a list of Data objects. Additionally, Data's getEmails() and getNumbers() methods parse your input String to a list of expected objects. For example if you call setNumbers("{24602254,55655545}") then getNumbers() will return a list of Integers (you can use any numeric type instead) like [24602254, 55655545].

Other suggestions are also valid, e.g. iterating over collection of TreeMaps or JSONObjects. In this example we limit our focus to deal with Java objects with specific types instead of dealing with primitives like Object class for example.

The final solution also depends on your runtime environment. In this case you will have to add jackson-core dependency - it makes more sense if your project already uses Jackson for other reasons.

Upvotes: 1

Lalit Jadav
Lalit Jadav

Reputation: 1427

Try this way if you are using ArrayList<TreeMap<String, String>> contacts;

for(TreeMap<String,String> contact : contacts){
 String id = contact.getValue("id");
}

Upvotes: 1

AbhayBohra
AbhayBohra

Reputation: 2117

Try this..It will give arrayList of id's

 JSONObject object=new JSONObject(response);
    JSONArray array= null;
    try {
        array = object.getJSONArray("response");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    ArrayList<String> idArray=new ArrayList<>();
    for(int i=0;i< array.length();i++)
    {
        idArray.add(getJSONObject(i).getString("id"));
    }

Upvotes: 1

Related Questions