迭代ArrayList

时间:2017-07-11 04:47:02

标签: java android arraylist

我想知道迭代这个ArrayList的最佳方法,这个ArrayList来自API的Response,这是ArrayList: enter image description here

问题是我不知道如何从循环中获取“id”和“value”, 我知道arraylist大小,但我不知道如何从这个数组打印“键”和“值”

        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
        //
    }

在onResponse中,我将此功能称为:

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

functionExample有一个ArrayList作为参数。 这是我resp.getResponse()的结果:

enter image description here

这是来自API的json:

{
"result": "success",
"message": "Lista de Contactos",
"response": [
    {
        "id": 1,
        "contact_name": "EDIFICADORA JUANA",
        "numbers": "{24602254,55655545}",
        "emails": "{oipoa@gmaio.com,rst008@guan.com}"
    },
    {
        "id": 2,
        "contact_name": "LA MEJOR",
        "numbers": "{25445877,25845877}",
        "emails": "{AMEJOR@GMAIL.COM}"
    }
  ]
}

我感谢任何帮助。

6 个答案:

答案 0 :(得分:1)

试试这个..它会给出id&#39;

的arrayList
 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"));
    }

答案 1 :(得分:1)

如果您使用的是ArrayList<TreeMap<String, String>> contacts;

,请尝试这种方式
for(TreeMap<String,String> contact : contacts){
 String id = contact.getValue("id");
}

答案 2 :(得分:1)

我强烈建议您使用例如杰克逊将您的JSON响应映射到适当的对象。请考虑以下示例:

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\": \"{oipoa@gmaio.com,rst008@guan.com}\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"id\": 2,\n" +
            "        \"contact_name\": \"LA MEJOR\",\n" +
            "        \"numbers\": \"{25445877,25845877}\",\n" +
            "        \"emails\": \"{AMEJOR@GMAIL.COM}\"\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("oipoa@gmaio.com", "rst008@guan.com"));
        //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;
        }
    }
}

在此示例中,我使用了您收到的相同JSON响应和jackson-core库(http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.8.9)来将String映射到POJO(而不是String,您可以使用InputStream,byte []等)。有两个POJO:ResponseData。响应聚合了Data个对象的列表。此外,Data的{​​{1}}和getEmails()方法将您的输入String解析为预期对象列表。例如,如果您致电getNumbers(),则setNumbers("{24602254,55655545}")将返回整数列表(您可以使用任何数字类型),例如getNumbers()

其他建议也有效,例如:迭代[24602254, 55655545]TreeMap的集合。在这个例子中,我们将注意力集中在处理具有特定类型的Java对象,而不是像JSONObject类那样处理原语。

最终解决方案还取决于您的运行时环境。在这种情况下,您将不得不添加Object依赖项 - 如果您的项目由于其他原因已经使用了Jackson,则更有意义。

答案 3 :(得分:1)

如果您使用设置&lt;地图&LT;字符串,字符串&gt;&gt;设置;

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

答案 4 :(得分:1)

  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(); 

  }
} 

答案 5 :(得分:0)

尝试使用此循环从您的ArrayList中提取每个值

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);
                }
            }
        }
    }