在java中迭代2个映射

时间:2014-04-30 20:36:44

标签: 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

1 个答案:

答案 0 :(得分:1)

我的解决方案同样效率低下,但效率不同。 试试这个:

... 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

根据项目的详细信息,将地图存储在表格中然后将其加入到自身中可能是值得的(在示例中,表格名称是粗糙的):

select
   a.key, b.key
from
   blammy a,
   blammy b
where
   a.key != b.key
相关问题