Java Foreach 键值对问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24991192/
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 16:17:48  来源:igfitidea点击:

Foreach Key Value Pair Issue

javaforeachkey-value

提问by llanato

I'm trying to convert a PHP script into a Java one but coming across a few issues on a foreach loop. In the PHP script I have a foreach that takes the key:value pair and based off this does a str_replace.

我正在尝试将 PHP 脚本转换为 Java 脚本,但在 foreach 循环中遇到了一些问题。在 PHP 脚本中,我有一个 foreach,它采用 key:value 对,并基于此执行 str_replace。

  foreach ($pValues AS $vKey => $vValue)
        $vString = str_replace("{".$vKey."}", "'".$vValue."'", $vString);

I've tried replicating this ins Java without success, I need to get the key from the array to use in the string replace function but can't for the life of me find out where or if its possible to get the key name from the array passed in.

我已经尝试复制这个 ins Java 没有成功,我需要从数组中获取密钥以在字符串替换函数中使用,但我一生无法找出在哪里或是否可以从数组传入。

Is this the right way or am I completely off!? Should I be using the ImmutablePairmethod?

这是正确的方法还是我完全关闭!?我应该使用该ImmutablePair方法吗?

  for (String vKey : pValues)
        // String replace

Here's hoping there is an easy way to get the key:value pair in Java, thanks in advance.

希望有一种简单的方法可以在 Java 中获取 key:value 对,提前致谢。

采纳答案by llanato

Thanks all for the help and advice, I've managed to duplicate the function in Java using Map.

感谢大家的帮助和建议,我已经设法在 Java 中使用Map.

    if (pValues != null)
    {
        Set vSet = pValues.entrySet();
        Iterator vIt = vSet.iterator();

        while(vIt.hasNext())
        {
            Map.Entry m =(Map.Entry)vIt.next();

            vSQL = vSQL.replace("{" + (String)m.getKey() + "}", "'" + (String)m.getValue() + "'");
            vSQL = vSQL.replace("[" + (String)m.getKey() +"]", (String)m.getValue());
        }
    }

回答by i_turo

That is not possible with a simple foreach-loop in Java.

在 Java 中使用简单的 foreach 循环是不可能的。

If pValuesis an array, you could use a simple for-loop:

如果pValues是一个数组,您可以使用一个简单的 for 循环:

for (int i = 0; i < pValues.length; i++)
  // String replace

If pValuesis a Map, you can iterate through it like this:

如果pValuesMap,您可以像这样遍历它:

for (Key key : map.keySet())
    string.replace(key, map.get(key));

回答by Adi

This can be acheived by using Map as data structure and then using entryset for iterating over it.

这可以通过使用 Map 作为数据结构,然后使用 entryset 对其进行迭代来实现。

 Map<K,V> entries= new HashMap<>();
    for(Entry<K,V> entry : entries.entrySet()){
        // you can get key by entry.getKey() and value by entry.getValue()
        // or set new value by entry.setValue(V value)
    }