【发布时间】:2014-05-01 05:03:37
【问题描述】:
我有一种情况,我在地图上循环了两次,对我的算法不是特别满意,想知道是否有其他方法可以实现这一点。这是我正在努力实现的目标的简化版本。
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
【问题讨论】:
-
您是否尝试将每个键与其他键进行比较?
-
不是真的比较而是用它做一些操作
-
Value2 Value3这一行是否意味着与Value3 Value2进行不同的比较? -
@cementblocks 很好的链接! :) 这一行完美地总结了它:
The complexity of cartesian product is O(n2), there is no shortcut.
标签: java