如何为每个hashmap?

Med*_*tor 473 java

我有这个领域:

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
Run Code Online (Sandbox Code Playgroud)

对于每个Hash<String, HashMap>我需要创建一个ComboBox,其项目是值(恰好是HashMap本身)HashMap <String, **HashMap**>.

通过(非功能)演示:

for (int i=0; i < selects.size(); i++) {
    HashMap h = selects[i].getValue();
    ComboBox cb = new ComboBox();

    for (int y=0; y < h.size(); i++) {
        cb.items.add(h[y].getValue);
    }
}
Run Code Online (Sandbox Code Playgroud)

Cyr*_* N. 1153

我知道我的那个晚了一点,但我会分享我所做的,以防它帮助其他人:

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();

for(Map.Entry<String, HashMap> entry : selects.entrySet()) {
    String key = entry.getKey();
    HashMap value = entry.getValue();

    // do what you have to do here
    // In your case, another loop.
}
Run Code Online (Sandbox Code Playgroud)

  • 我永远不记得怎么写这个,所以我总是回到同样的答案.Upvoted,因为这是干净的答案,这个代码被复制粘贴到我的项目中的很多地方,谢谢! (84认同)
  • @Katu只需编写yourmap..entrySet().for,IDE自动完成将处理它. (6认同)

Nit*_*esh 229

Lambda Expression Java 8

在Java 1.8(Java 8)中,通过使用类似于来自Iterable Interface的迭代器的聚合操作(流操作)的forEach方法,这变得更加容易.

只需将下面的语句粘贴到您的代码中,然后将HashMap变量从hm重命名为HashMap变量,以打印出键值对.

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
 *     Logic to put the Key,Value pair in your HashMap hm
 */

// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
Run Code Online (Sandbox Code Playgroud)

以下是使用Lambda表达式的示例:

    HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
    Random rand = new Random(47);
    int i=0;
    while(i<5){
        i++;
        int key = rand.nextInt(20);
        int value = rand.nextInt(50);
        System.out.println("Inserting key: "+key+" Value: "+value);
        Integer imap =hm.put(key,value);
        if( imap == null){
            System.out.println("Inserted");
        }
        else{
            System.out.println("Replaced with "+imap);
        }               
    }

    hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

Output:

Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11
Run Code Online (Sandbox Code Playgroud)

也可以使用Spliterator.

Spliterator sit = hm.entrySet().spliterator();
Run Code Online (Sandbox Code Playgroud)

UPDATE


包括Oracle Docs的文档链接.有关Lambda的更多信息,请转到此链接,并且必须阅读Aggregate Operations,对于Spliterator,请转到此链接.

  • 使用lambdas的缺点是你不能在lambda内部返回另一个方法. (3认同)

Ber*_*t F 50

Map.values():

HashMap<String, HashMap<SomeInnerKeyType, String>> selects =
    new HashMap<String, HashMap<SomeInnerKeyType, String>>();

...

for(HashMap<SomeInnerKeyType, String> h : selects.values())
{
   ComboBox cb = new ComboBox();
   for(String s : h.values())
   {
      cb.items.add(s);
   }
}
Run Code Online (Sandbox Code Playgroud)

  • +1:这是一个比我的答案更简洁的方法(假设我们使用的是Java 5或更高版本) (2认同)

Oli*_*rth 18

您可以HashMap使用迭代器迭代(和许多其他集合),例如:

HashMap<T,U> map = new HashMap<T,U>();

...

Iterator it = map.values().iterator();

while (it.hasNext()) {
    System.out.println(it.next());
}
Run Code Online (Sandbox Code Playgroud)

  • @是的你可以.您可以基于`it.next()`创建一个内部迭代器. (3认同)
  • 我不能将这样的设计降到下面的水平 (2认同)

i_a*_*ero 17

Streams Java 8

除了forEach接受lambda表达式的方法,我们还在Java 8中获得了 API.

迭代条目(使用forEach和Streams):

sample.forEach((k,v) -> System.out.println(k + "=" + v)); 
sample.entrySet().stream().forEachOrdered((entry) -> {
            Object currentKey = entry.getKey();
            Object currentValue = entry.getValue();
            System.out.println(currentKey + "=" + currentValue);
        });
sample.entrySet().parallelStream().forEach((entry) -> {
            Object currentKey = entry.getKey();
            Object currentValue = entry.getValue();
            System.out.println(currentKey + "=" + currentValue);
        });
Run Code Online (Sandbox Code Playgroud)

流的优点是它们可以轻松并行化,并且在我们有多个CPU可用时非常有用.我们只需要用上面的parallelStream()代替stream().对于并行流,使用更有意义,forEach因为forEachOrdered性能没有差别.如果我们想迭代键,我们可以使用sample.keySet()和值sample.values().

为什么forEachOrdered而不是forEach溪流?

Streams还提供forEach方法,但行为forEach明确是非确定性的,其中当流具有已定义forEachOrdered遭遇顺序时,以流遭遇顺序对此流的每个元素执行操作.所以forEach不保证订单会被保留.另外,请查看内容.


小智 15

我通常和cx42net一样,但我没有明确创建一个Entry.

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for (String key : selects.keySet())
{
    HashMap<innerKey, String> boxHolder = selects.get(key);
    ComboBox cb = new ComboBox();
    for (InnerKey innerKey : boxHolder.keySet())
    {
        cb.items.add(boxHolder.get(innerKey));
    }
}
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎是最直观的,我认为我对迭代地图的值有偏见.


icy*_*com 10

使用entrySet

/**
 *Output: 
D: 99.22
A: 3434.34
C: 1378.0
B: 123.22
E: -19.08

B's new balance: 1123.22
 */

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MainClass {
  public static void main(String args[]) {

    HashMap<String, Double> hm = new HashMap<String, Double>();

    hm.put("A", new Double(3434.34));
    hm.put("B", new Double(123.22));
    hm.put("C", new Double(1378.00));
    hm.put("D", new Double(99.22));
    hm.put("E", new Double(-19.08));

    Set<Map.Entry<String, Double>> set = hm.entrySet();

    for (Map.Entry<String, Double> me : set) {
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }

    System.out.println();

    double balance = hm.get("B");
    hm.put("B", balance + 1000);

    System.out.println("B's new balance: " + hm.get("B"));
  }
}
Run Code Online (Sandbox Code Playgroud)

请参阅此处的完整示例:

  • 它确实有效,我每天都使用它:)到底什么不起作用?由于您有“HashMap&lt;String, HashMap&gt;”,因此您需要两个循环 - 一个用于外部 HashMap,一个用于内部 HashMap。顺便说一句 - 你应该明确输入第二个 HashMap - 不知道你在其中存储什么,但像 HashMap&lt;String, HashMap&lt;string, String&gt;&gt; - 不过,从你的例子来看,你似乎应该使用 `HashMap&lt;String , 设置&lt;字符串&gt;&gt;`。还有一件事 - 尽可能使用接口:`Map&lt;String, Map&gt;`。 (2认同)