Java 如何为每个哈希图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4234985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:51:33  来源:igfitidea点击:

How to for each the hashmap?

java

提问by Mediator

I have this field:

我有这个领域:

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

For each Hash<String, HashMap>I need to create a ComboBox, whose items are the value (which happens to be a HashMap itself) of HashMap <String, **HashMap**>.

对于每个Hash<String, HashMap>我需要创建一个ComboBox,其项目是HashMap <String, **HashMap**>.

By way of (non-functioning) demonstration:

通过(非功能性)演示:

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

采纳答案by Cyril N.

I know I'm a bit late for that one, but I'll share what I did too, in case it helps someone else :

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

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

回答by icyrock.com

Use entrySet,

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

see complete example here:

在此处查看完整示例:

回答by Bert F

Map.values():

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

回答by Oliver Charlesworth

You can iterate over a HashMap(and many other collections) using an iterator, e.g.:

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

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

...

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

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

回答by panahi

I generally do the same as cx42net, but I don't explicitly create an Entry.

我通常和 cx42net 做同样的事情,但我没有明确地创建一个条目。

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

This just seems the most intuitive to me, I think I'm prejudiced against iterating over the values of a map.

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

回答by Nitin Mahesh

LambdaExpression Java 8

Lambda表达式 Java 8

In Java 1.8 (Java 8) this has become lot easier by using forEachmethod from Aggregate operations(Stream operations) that looks similar to iterators from IterableInterface.

在Java 1.8(Java 8)这已经成为使用容易得多的forEach从聚合操作方法(流操作),其类似于从迭代器的外观可迭代接口。

Just copy paste below statement to your code and rename the HashMapvariable from hmto your HashMap variable to print out key-value pair.

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

Here is an example where a Lambda Expressionis used:

以下是使用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

Also one can use Spliteratorfor the same.

同样可以使用Spliterator

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

UPDATE

更新



Including documentation links to Oracle Docs. For more on Lambdago to this linkand must read Aggregate Operationsand for Spliterator go to this link.

包括指向 Oracle Docs 的文档链接。有关Lambda 的更多信息,请转到此链接,并且必须阅读聚合操作,对于 Spliterator,请转到此链接

回答by akhil_mittal

Streams Java 8

流 Java 8

Along with forEachmethod that accepts a lambda expressionwe have also got streamAPIs, in Java 8.

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

Iterate over entries (Using forEach and Streams):

迭代条目(使用 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);
        });

The advantage with streams is they can be parallelized easily and can be useful when we have multiple CPUs at disposal. We simply need to use parallelStream()in place of stream()above. With parallel streams it makes more sense to use forEachas forEachOrderedwould make no difference in performance. If we want to iterate over keys we can use sample.keySet()and for values sample.values().

流的优点是它们可以轻松并行化,并且在我们有多个 CPU 可供使用时非常有用。我们只需要使用parallelStream()代替stream()上面的。使用并行流更有意义,forEach因为它forEachOrdered不会对性能产生影响。如果我们想遍历键,我们可以使用sample.keySet()和 for values sample.values()

Why forEachOrderedand not forEachwith streams ?

为什么forEachOrdered而不是forEach使用流?

Streams also provide forEachmethod but the behaviour of forEachis explicitly nondeterministic where as the forEachOrderedperforms an action for each element of this stream, in the encounter order of the streamif the stream has a defined encounter order. So forEachdoes not guarantee that the order would be kept. Also check thisfor more.

流还提供forEach方法,但行为forEach是明确不确定性,其中作为forEachOrdered执行用于该流的每个元件的操作,在该流的遭遇顺序如果流具有规定的遭遇顺序。所以forEach不保证订单会被保留。还要检查这个以获取更多信息。