[英]Iterating over 2 maps in java
我遇到這樣的情況,我在地圖上循環了兩次,對我的算法不太滿意,並且想知道是否還有另一種方法可以實現這一點。 這是我要實現的目標的簡化版本。
import java.util.*;
public class DummyTest{
public static void main(String []args){
Map<String, String> someMap = new HashMap<>();
someMap.put("Key1", "Value1");
someMap.put("Key2", "Value2");
someMap.put("Key3", "Value3");
for (final Map.Entry<String, String> entry : someMap.entrySet()) {
// I think this is a code smell - Is there a way to avoid this inner
// loop and still get the same output?
for (final Map.Entry<String, String> innerLoop : someMap.entrySet())
{
if (entry.getValue() != innerLoop.getValue()) {
System.out.println(entry.getValue() + " " +
innerLoop.getValue());
}
}
}
}
}
期望的輸出
Value2 Value1
Value2 Value3
Value1 Value2
Value1 Value3
Value3 Value2
Value3 Value1
我的解決方案同樣效率低下,但效率低下。 嘗試這個:
... setup someMap however you want.
List<String> leftKeyList = new LinkedList<String>();
List<String> rightKeyList = new LinkedList<String>();
leftKeyList.addAll(someMap.keySet());
Collections.sort(leftKeyList); // you seem to want the keys sorted.
for (final String leftKey : leftKeyList)
{
Set<String> rightKeySet = someMap.keySet());
rightKeySet.remove(leftKey);
rightKeyList.clear();
rightKeyList.addAll(rightKeySet);
Collections.sort(rightKeySet); // you seem to want these keys sorted as well.
for (final String rightKey : rightSeyList)
{
System.out.println(leftKey + " " + rightKey);
}
}
編輯:如下所述,以上為N ^ 2。 我相信,只要您必須對一組鍵中的一個鍵與同一組中的每個其他鍵進行配對(如上圖所示),就會陷入n ^ 2的困境。 效率低下並不會殺死一小撮鑰匙。 100個或更少的鍵,您應該不會有糟糕的表現。
Edit2:您提出的問題很有趣,因為它反映了經典的SQL連接錯誤,該錯誤是由於聯接兩個表而不使用聯接列而導致的。 這是一個示例sql:
select
a.blah, b.hoot
from
a, b
根據項目的詳細信息,可能值得將地圖存儲在表中,然后像這樣將其自身連接起來(在示例中,表名是lamymy):
select
a.key, b.key
from
blammy a,
blammy b
where
a.key != b.key
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.