我在反转给定的映射并将其反转的键和值存储到另一个映射中时遇到了一些麻烦。我有一个方法原型如下:
public static Map<String, Set<String>> reverse (Map <String, Set<String>> graph);
Run Code Online (Sandbox Code Playgroud)
因此,如果我有有向图的示例键,则:
{c -> arraySet{f, e}}
{b -> d}
{a -> arraySet{c, b}}
{d -> g}
{e -> d}
{f -> arraySet{g, d}}
Run Code Online (Sandbox Code Playgroud)
我需要有效地反转这个图,以便我有 d -> b 而不是 b -> d。
我认为这对我来说只是交换原始图中的值和键并将它们添加到 reverseMap 中。我想我可以遍历图中给定键的每组值,然后将它们存储在列表中。
不幸的是,我在实施和考虑它时遇到了麻烦。我真的很感激朝正确方向的推动。
仅当每个键在map1中具有唯一值时,我才陷入如何将键值对从map1传输到map2的问题。
假设我有以下地图:
我想算法是:
代码片段:
public static <K,V> Map<K,V> unique (Map<K,V> m) {
Map<K,V> newMap = new ArrayMap<K,V>();
//Remember all values in the newMap.
Set<V> holding = new ArraySet<V>(newMap.values());
for (Map.Entry<K, V> graphEntry : m.entries()) {
//not sure.
}
return newMap;
}
Run Code Online (Sandbox Code Playgroud)
我的想法应该如何在正确的轨道上完成?在这里完全迷失了。
我有一个字符串,它应该返回多个字符串的串联,例如"bob""bill""steve".最终结果应该像"bob bill steve".如何使用Java在最终单词之前或之后添加空格而不添加空格?
我一直在努力摆脱调用代码行时发生的NullPointerException:
if (priorityComparator.compare(temp.next.value, newNode.value) >= 0 )
Run Code Online (Sandbox Code Playgroud)
完整的代码是:
public class HeaderLinkedPriorityQueue<E> extends
AbstractPriorityQueue<E> implements PriorityQueue<E> {
//Some other methods, constructors etc.
public boolean add (E e) {
ListNode<E> temp = highest;
ListNode<E> newNode = new ListNode<E>(e, null);
if (temp.next == null){
//first node in a list.
temp.next = newNode;
objectCount++;
return true;
}
//if the value of the first element following the header node is greater than the newNode add to back.
if (priorityComparator.compare(temp.next.value, newNode.value) >= 0 ) {
temp.next.next …Run Code Online (Sandbox Code Playgroud)