我有这个字段:
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
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并不保证顺序会被保持。查看更多信息。