2023-07-23 05:00:00

如何为每个hashmap?

我有这个字段:

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

对于每个Hash<String, HashMap>,我需要创建一个组合框,其项目是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);
    }
}

当前回答

使用条目集,

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

完整的例子如下:

http://www.java2s.com/Code/JavaAPI/java.util/HashMapentrySet.htm

其他回答

我通常执行与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));
    }
}

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

Lambda表达式Java 8

在Java 1.8 (Java 8)中,通过使用聚合操作(流操作)中的forEach方法,这变得容易得多,它看起来类似于Iterable Interface中的迭代器。

只需将下面的粘贴语句复制到代码中,并将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表达式的例子:

    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();

更新


包括到Oracle文档的文档链接。 关于Lambda的更多信息请访问这个链接,必须阅读聚合操作,关于Spliterator请访问这个链接。

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

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

...

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

while (it.hasNext()) {
    System.out.println(it.next());
}

Streams Java 8

在Java 8中,除了接受lambda表达式的forEach方法外,我们还获得了流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);
        });

流的优点是它们可以很容易地并行,并且在我们有多个cpu可用时非常有用。我们只需要使用parallelStream()来代替上面的stream()。对于并行流,使用forEach更有意义,因为forEachOrdered在性能上不会有任何差异。如果我们想要遍历键,我们可以使用sample.keySet()和sample.values()。

为什么在流中forEachOrdered而不是forEach ?

流也提供forEach方法,但forEach的行为是显式的不确定的,其中forEachOrdered为流的每个元素执行一个操作,如果流具有定义的遇到顺序,则按照流的遇到顺序。因此forEach并不保证顺序会被保持。查看更多信息。

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