Java Foreach键值对问题
我试图将PHP脚本转换为Java脚本,但在foreach循环中遇到了一些问题。在PHP脚本中,我有一个foreach,它接受key:value对,并在此基础上进行str_替换Java Foreach键值对问题,java,foreach,key-value,Java,Foreach,Key Value,我试图将PHP脚本转换为Java脚本,但在foreach循环中遇到了一些问题。在PHP脚本中,我有一个foreach,它接受key:value对,并在此基础上进行str_替换 foreach ($pValues AS $vKey => $vValue) $vString = str_replace("{".$vKey."}", "'".$vValue."'", $vString); 我尝试复制这个ins Java,但没有成功,我需要从数组中获取密钥以用于字符串替换函数
foreach ($pValues AS $vKey => $vValue)
$vString = str_replace("{".$vKey."}", "'".$vValue."'", $vString);
我尝试复制这个ins Java,但没有成功,我需要从数组中获取密钥以用于字符串替换函数,但我一生都无法找到从传入的数组中获取密钥名称的位置或可能性
这是正确的方法还是我完全错了!?我应该使用ImmutablePair
方法吗
for (String vKey : pValues)
// String replace
这里希望有一种简单的方法来获取Java中的key:value对,提前感谢。这在Java中用一个简单的foreach循环是不可能的 如果pValues是数组,则可以使用简单的for循环:
for (int i = 0; i < pValues.length; i++)
// String replace
这可以通过使用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)
}
Map entries=newhashmap();
for(条目:entries.entrySet()){
//您可以通过entry.getKey()和entry.getValue()获取键和值
//或通过条目设置新值。设置值(V值)
}
谢谢大家的帮助和建议,我已经使用Map
在Java中复制了这个函数
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());
}
}
如果您有一个Key:Value数据结构,那么应该使用一个而不是数组。然后,您可以遍历。如果你只需要数组的索引号(作为键),你可以使用for循环。你能提供pValues的声明吗?
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());
}
}