首页 文章

如何为每个hashmap? [重复]

提问于
浏览
410

这个问题在这里已有答案:

我有这个领域:

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

对于每个 Hash<String, HashMap> 我需要创建 ComboBox ,其项目是 HashMap <String, **HashMap**> 的值(恰好是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);
    }
}

7 回答

  • 14

    Lambda Expression Java 8

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

    只需将下面的语句粘贴到您的代码中,然后将 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));
    

    以下是使用 Lambda Expression 的示例:

    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
    

    也可以使用 Spliterator .

    Spliterator sit = hm.entrySet().spliterator();
    

    UPDATE


    包括Oracle Docs的文档链接 . 有关 Lambda 的详细信息,请转至link并阅读Aggregate Operations,对于Spliterator,请转至link .

  • 49

    如前所述,在Java 8中,我们有 forEach 方法接受lambda expression . 但我们也有stream API .

    Iterate over entries (Using forEach and 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);
            });
    

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

    Why forEachOrdered and not forEach with streams ?

    Streams还提供 forEach 方法,但 forEach 的行为明确是不确定的,因为 forEachOrdered 对此流的每个元素执行操作,如果流具有已定义的遭遇顺序,则在_560609中执行 . 所以 forEach 并不保证订单会被保留 . 另请查看this以获取更多信息 .

  • 9

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

    看这里的完整例子:

  • 17

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

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

    HashMap<T,U> map = new HashMap<T,U>();
    
    ...
    
    Iterator it = map.values().iterator();
    
    while (it.hasNext()) {
        System.out.println(it.next());
    }
    
  • 3

    我通常和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));
        }
    }
    

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

  • 191

    我知道我有点迟到了,但我会分享我所做的,以防它帮助其他人:

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

相关问题