简体   繁体   English

如何从HashMap中提取ArrayList并在Java中循环它?

[英]How can I extract ArrayList from HashMap and loop through it in Java?

I have set up a HashMap like so: 我已经像这样设置了一个HashMap:

Map<String, ArrayList<String>> theAccused = new HashMap<String, ArrayList<String>>();

... and I populate this by storing for every name (key), a list of names (value). ...我通过存储每个名称(键),一个名称列表(值)来填充它。 So: 所以:

ArrayList<String> saAccused = new ArrayList<String>();
// populate 'saAccused' ArrayList
...
// done populating
theAccused.put(sAccuser, saAccused);

So now, I want to look through all of the entries in the HashMap and see if (for each 'sAccuser'), the list 'saAccused' contains a certain name. 所以现在,我想查看HashMap中的所有条目,看看(对于每个'sAcucuser')列表'saAccused'是否包含某个名称。 This is my failed attempt so far: 到目前为止,这是我失败的尝试:

Set<String> setAccusers = theAccused.keySet();
Iterator<String> iterAccusers = setAccusers.iterator();
iterAccusers.next();
ArrayList<String> saTheAccused;

// check if 'sAccuser' has been accused by anyone before
for (int i = 0; i < theAccused.size(); i++) {
    saTheAccused = theAccused.get(iterAccusers);

    if (saTheAccused.contains(sAccuser)) {

    }
    iterAccusers.next();
}

... however I'm not sure how the Set and Iterator classes work :/ The problem is that I don't have the "values"... the names... the 'sAccuser' s... for the HashMap available. ...但是我不确定SetIterator类是如何工作的:/问题是我没有“值”...名称... 'sAccuser'的...用于HashMap可用。

In a nutshell, I want to iterate through the HashMap and check if a specific name is stored in any of the lists. 简而言之,我想迭代HashMap并检查特定名称是否存储在任何列表中。 So how can I do this? 那我该怎么做呢? Let me know if you need me to go into further detail or clear up any confusion. 如果您需要我进一步了解或清除任何混淆,请告诉我。

Thanks. 谢谢。

In a nutshell, I want to iterate through the HashMap and check if a specific name is stored in any of the lists. 简而言之,我想迭代HashMap并检查特定名称是否存储在任何列表中。 So how can I do this? 那我该怎么做呢?

There's two ways of iterating through the map that might be of interest here. 有两种方法可以在这里迭代地图。 Firstly, you can iterate through all of the mappings (ie pairs of key-value relations) using the entrySet() method, which will let you know what the key is for each arraylist. 首先,您可以使用entrySet()方法迭代所有映射(即键值关系对 ,这将让您知道每个arraylist的键是什么。 Alternatively, if you don't need the key, you can simply get all of the lists in turn via the values() method. 或者,如果您不需要密钥,则可以通过values()方法依次获取所有列表。 Using the first option might look something like this: 使用第一个选项可能如下所示:

for (Map.Entry<String, ArrayList<String>> entry : theAccused.entrySet())
{
   String sListName = entry.getKey();
   ArrayList<String> saAccused = entry.getValue();
   if (saAccused.contains(sAccuser))
   {
      // Fire your logic for when you find a match, which can
      // depend on the list's key (name) as well
   }
}

To answer the broader questions - the Set interface simply represents an (unordered) collection of non-duplicated values. 为了回答更广泛的问题 - Set接口只表示非重复值的(无序)集合。 As you can see by the linked Javadoc, there are methods available that you might expect for such an unordered collection. 正如您可以通过链接的Javadoc看到的那样,对于这样的无序集合,您可能会有一些方法可用。 An Iterator is an object that traverses some data structure presenting each element in turn. 迭代器是一个对象,它遍历一些数据结构,依次呈现每个元素。 Typical usage of an iterator would look something like the following: 迭代器的典型用法如下所示:

Iterator<?> it = ...; // get the iterator somehow; often by calling iterator() on a Collection
while (it.hasNext())
{
   Object obj = it.next();
   // Do something with the obj
}

that is, check whether the iterator is nonexhausted (has more elements) then call the next() method to get that element. 也就是说,检查迭代器是否为非xyusted(有更多元素),然后调用next()方法获取该元素。 However, since the above pattern is so common, it can be elided with Java 5's foreach loop , sparing you from dealing with the iterator itself, as I took advantage of in my first example. 但是,由于上面的模式是如此常见,因此可以省略Java 5的foreach循环 ,从而使你免于处理迭代器本身,正如我在第一个例子中所利用的那样。

Something like this? 像这样的东西?

for (List<String> list : theAccused.values()) {
    if (list.contains("somename")) {
        // found somename
    }
}

This should make it work: 这应该使它工作:

saTheAccused = theAccused.get(iterAccused.next());

However, to make your code more readable, you can have either: 但是,为了使您的代码更具可读性,您可以:

for (List<String> values : theAccused.values()) {
    if (value.contains(sAcuser)) {
       ..
    }
}

or, if you need the key: 或者,如果您需要钥匙:

for (String key : theAccused.keySet()) {
    List<String> accused = theAccused.get(key);
    if (accused.contains(sAccuser)) {
    }
}

You need to use the value from Iterator.next() to index into the Map . 您需要使用Iterator.next()的值来索引Map

String key = iterAccusers.next();
saTheAccused = theAccused.get(key);

Currently you're getting values from the Map based on the iterator , not the values returned by the iterator. 目前,您将根据迭代器Map获取值,而不是迭代器返回的值。

Make a method that does it: 制作一个方法:

 private String findListWithKeyword(Map<String, ArrayList<String>> map, String keyword) {
   Iterator<String> iterAccusers = map.keySet().iterator();
   while(iterAccusers.hasNext()) {
      String key = iterAccusers.next();
      ArrayList<String> list = theAccused.get(key);
      if (list.contains(keyword)) {
         return key;
      } 
   }
}

And when you call the method: 当你调用方法时:

String key = findListWithKeyword(map, "foobar");
ArrayList<String> theCorrectList = map.get(key);

It sounds like you need to do two things: first, find out if a given name is "accused", and second, find out who the accuser is. 听起来你需要做两件事:首先,找出一个给定的名字是否“被指控”,其次,找出原告是谁。 For that, you need to iterate over the Entry objects within your Map. 为此,您需要迭代Map中的Entry对象。

    for (Entry<String, List<String>> entry : theAccused.entrySet()) {
        if (entry.getValue().contains(accused)) {
            return entry.getKey();
        }
    }

    return null; // Or throw NullPointerException, or whatever.

In this loop, the Entry object holds a single key-value mapping. 在此循环中,Entry对象包含单个键 - 值映射。 So entry.getValue() contains the list of accused, and entry.getKey() contains their accuser. 所以entry.getValue()包含被控者列表,而entry.getKey()包含他们的原控者。

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

相关问题 Java 8: how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams? - Java 8 : how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams? 如何提取哈希表的数组列表并在Android中循环遍历? - How to extract list of arraylist of hashmap and loop through it in android? JAVA:HashMap <String, ArrayList> - 我如何关联这些值? - JAVA: HashMap<String, ArrayList> - How can I associate the values? Java:如何克隆ArrayList的HashMap? - Java: How can I make a clone of a HashMap of ArrayList ? 如何从 Java 中的嵌套 HashMap 创建值的数组列表? - How do i create an arraylist of values from a nested HashMap in java? 如何使用从 Hashmap 上的 Arraylist 中选择的值? - How can I use a value I chose from the Arraylist on Hashmap? 您是否可以像在ArrayList中一样遍历HashMap? - Can you loop through a HashMap like you can in an ArrayList? 如何从Java中的哈希图获取arraylist? - how to get the arraylist from the hashmap in java? 如何在存储在arraylist类型哈希图中的哈希图中检索值? - How can I retrieve the value in a Hashmap stored in an arraylist type hashmap? 如何从Hashmap提取和打印特定值? - How i can extract and print specific values from a Hashmap?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM