有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java迭代数组列表

我想知道迭代此ArrayList的最佳方法,此ArrayList来自API的响应,这是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) 个答案

  1. # 1 楼答案

    尝试这个循环从你的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);
                    }
                }
            }
        }
    
  2. # 2 楼答案

    如果使用设置<;地图<;弦,弦>>;设置

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

      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(); 
    
      }
    } 
    
  4. # 4 楼答案

    如果你正在使用ArrayList<TreeMap<String, String>> contacts,那么试试这种方法

    for(TreeMap<String,String> contact : contacts){
     String id = contact.getValue("id");
    }
    
  5. # 5 楼答案

    我强烈建议您使用例如Jackson将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)将字符串映射到POJO(而不是可以使用InputStream、byte[]等的字符串)。有两种POJO:ResponseData。Response聚合了Data对象的列表。此外,DatagetEmails()getNumbers()方法将输入字符串解析为预期对象的列表。例如,如果调用setNumbers("{24602254,55655545}"),那么getNumbers()将返回一个整数列表(可以使用任何数字类型),如[24602254, 55655545]

    其他建议也是有效的,例如迭代TreeMapJSONObject的集合。在本例中,我们将重点限制在处理具有特定类型的Java对象,而不是处理Object类之类的原语

    最终的解决方案还取决于您的运行时环境。在这种情况下,您必须添加jackson-core依赖项——如果您的项目已经出于其他原因使用了Jackson,那么这就更有意义了

  6. # 6 楼答案

    试试这个。。它会给出arrayList的id

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