如何为每个hashmap? [重复]

本文详细介绍如何在Java中高效地迭代Map结构,包括使用for-each循环遍历键集、值集合和条目集,以及利用Java 8的流API和Lambda表达式进行更简洁的迭代。同时,对比了不同迭代方式的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:How to for each the hashmap? [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

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**>的值(恰好是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);
    }
}

#1楼

参考:https://stackoom.com/question/HliD/如何为每个hashmap-重复


#2楼

I generally do the same as cx42net, but I don't explicitly create an Entry. 我通常和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));
    }
}

This just seems the most intuitive to me, I think I'm prejudiced against iterating over the values of a map. 这对我来说似乎是最直观的,我认为我对迭代地图的值有偏见。


#3楼

Lambda Expression Java 8 Lambda Expression Java 8

In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations( Stream operations ) that looks similar to iterators from Iterable Interface. 在Java 1.8(Java 8)中,通过使用类似于来自Iterable Interface的迭代器的聚合操作( 流操作 )的forEach方法,这变得更加容易。

Just copy paste below statement to your code and rename the HashMap variable from hm to 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 Expression is 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 Spliterator for the same. 也可以使用Spliterator

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

UPDATE UPDATE


Including documentation links to Oracle Docs. 包括Oracle Docs的文档链接。 For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link . 有关Lambda的更多信息,请转到此链接,并且必须阅读Aggregate Operations ,对于Spliterator,请转到此链接


#4楼

Streams Java 8 Streams Java 8

Along with forEach method that accepts a lambda expression we have also got stream APIs, in Java 8. 除了接受lambda表达式的 forEach方法之外,我们还在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. 流的优点是它们可以轻松并行化,并且在我们有多个CPU可用时非常有用。 We simply need to use parallelStream() in place of stream() above. 我们只需要使用parallelStream()代替上面的stream() With parallel streams it makes more sense to use forEach as forEachOrdered would make no difference in performance. 对于并行流,使用forEach更有意义,因为forEachOrdered在性能上没有任何区别。 If we want to iterate over keys we can use sample.keySet() and for values sample.values() . 如果我们想迭代键,我们可以使用sample.keySet()和值sample.values()

Why forEachOrdered and not forEach with streams ? 为什么forEachOrdered而不是forEach与流?

Streams also provide forEach method but the behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. 流还提供forEach方法,但行为forEach是明确地不确定性,其中作为forEachOrdered执行用于该流的每个元件的操作,在该流的遭遇顺序如果流具有规定的遭遇顺序。 So forEach does not guarantee that the order would be kept. 因此, forEach不保证订单会被保留。 Also check this for more. 另外,请查看内容。


#5楼

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: 看这里的完整例子:


#6楼

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);
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值