简体   繁体   English

如何循环访问ArrayList的集合

[英]how to loop in a collection of ArrayList

i had a Hash Map, the key is a string and the value is array list, i want to check if Array List include a value then retrieve the key for the value. 我有一个哈希表,键是一个字符串,值是数组列表,我想检查数组列表是否包含值,然后检索该值的键。 so i did this: 所以我这样做:

Collection<ArrayList<String>> emailList = AddressBook.addressMap.values();
    Iterator<ArrayList<String>> iterator = emailList.iterator();

using a loop i can print the lists but i can't check if it equals to a string. 使用循环我可以打印列表,但我不能检查它是否等于字符串。 how can i access each string in Array List and use equals 我如何访问数组列表中的每个字符串并使用等号

Use a nested loop: 使用嵌套循环:

for(List<String> list:emailList)
   for(String s:list) {
      // Logic
   }

This will allow you to iterate over each String in the entire Collection of ArrayList s. 这将允许您遍历整个ArrayListCollection的每个String。

You could try something like this. 您可以尝试这样的事情。 Since the Value in the hashmap is that of ArrayList, you have to loop through the collection of arraylists and then check the arraylist for your string: 由于哈希图中的值是ArrayList的值,因此您必须遍历arraylist的集合,然后检查arraylist中的字符串:

For (ArrayList list : emailList ){

    if(emailList.contains(stringVALUE)){
        // do some stuff
    }
}

OR 要么

 For (ArrayList list : emailList ){

   For(String s: list){
       if(s.equals(theValueYouAreLookingFor)){
          //do some stuff
       }

   }

}

You could do it like this using streams. 您可以使用流来做到这一点。 This returns all keys for each mapped list that contains the desired value. 这将为每个包含所需值的映射列表返回所有键。

      Map<String, List<String>> map = new HashMap<>();
      map.put("list1", Arrays.asList("Apples", "Oranges", "Bananas"));
      map.put("list2", Arrays.asList("Grapes", "Kiwi", "Apples"));
      map.put("list3", Arrays.asList("Mangos", "Kiwi", "Berries"));

      String val = "Kiwi";
      List<String> keys = map.entrySet().stream().filter(
            entry -> entry.getValue().contains(val)).map(
                  entry -> entry.getKey()).collect(Collectors.toList());

      System.out.println(keys);

It works as follows: 其工作方式如下:

  • Map the entrySet of the map to a stream of entrySets. 将映射的entrySet映射到entrySets流。
  • Filter the entry value by checking the value (a list of items) to see if it contains the desired item. 通过检查值(项目列表)来筛选条目值,以查看其是否包含所需的项目。
  • If it does, map the result to the entry key for that list. 如果是这样,请将结果映射到该列表的输入键。
  • Collect the keys in a list. 将密钥收集在列表中。
For the search val of Kiwi
This produces the output  [list3, list2]

If you want to stop after you find the first entry you could alter it slightly. 如果要在找到第一个条目后停止,可以对其稍加更改。

       for (String item : List.of("Apples", "Fish")) {

          String key = map.entrySet().stream().filter(
               entry -> entry.getValue().contains(item)).map(
                     entry -> entry.getKey()).findFirst().orElse(
                           "Not Found");

         System.out.println("Key for item " + item + " = " + key);

      }

This produces the following output. 这将产生以下输出。

Key for item Apples = list1
Key for item Fish = Key Not Found

This uses a findFirst to stop after the first one is found. 这使用findFirst在找到第一个后停止。 Since it returns an Optional, the orElse method can be used to specify a default value to indicate that no list contained the item. 由于它返回Optional,因此orElse方法可用于指定默认值,以指示没有列表包含该项目。

You can also specify parallel to process these streams using threads. 您还可以指定并行以使用线程处理这些流。 This can greatly increase processing speed. 这样可以大大提高处理速度。 Especially if you have multiple cores. 特别是如果您有多个核心。

Please take a look at: 请看一下:

String key = null;
for (Map.Entry<String, ArrayList<String>> emailListEntry : AddressBook.addressMap.entrySet()) {
    for (String email: emailListEntry.getValue()){
        if(email.equals("TEST")){
            key =  emailListEntry.getKey(); 
            break;
        }
    }
    if (key!=null){
        break;
    }
}
Map<String,List> map = new HashMap<>();
    map.put( "list1", Arrays.asList( "Hello1", "Hello2" ) );
    map.put( "list2", Arrays.asList( "Hi", "Hi2" ) );

    for ( String key : map.keySet() ) {

        List list = map.get( key );
        if ( list.contains( "Hi2" ) ) {
            System.out.println( "This key contained the string " + key );
            break;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM