[英]Foreach Key Value Pair Issue
我正在嘗試將PHP腳本轉換為Java腳本,但是在foreach循環中遇到了一些問題。 在PHP腳本中,我有一個foreach,它采用key:value對,並以此為基礎進行str_replace。
foreach ($pValues AS $vKey => $vValue)
$vString = str_replace("{".$vKey."}", "'".$vValue."'", $vString);
我試圖復制此ins Java失敗,我需要從數組中獲取密鑰以用於字符串替換功能,但我一生無法找到從中獲取密鑰名稱的位置或是否可能數組傳入。
這是正確的方法還是我完全離開了!? 我應該使用ImmutablePair
方法嗎?
for (String vKey : pValues)
// String replace
希望通過簡單的方法在Java中獲取key:value對。
可以通過使用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)
}
使用Java中的簡單foreach循環是不可能的。
如果pValues是一個數組,則可以使用簡單的for循環:
for (int i = 0; i < pValues.length; i++)
// String replace
如果pValues是Map ,則可以像這樣遍歷它:
for (Key key : map.keySet())
string.replace(key, map.get(key));
感謝所有人的幫助和建議,我設法使用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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.