English 中文(简体)
清单中链条链条
原标题:Construct chain of links from list

我有一份关键/价值配对清单,我需要发现价值与钥匙相符的链条。

例如,从下文来看,可以有12、23、34或62、23、34、34。

Key  Value
1    2
3    4
2    3
6    2

一种以上的价值可以指同一个关键,但我需要为每个独特的起点和终点储存不同的链条。 名单可以按任何顺序排列。

我用贾瓦语说话,但我很想如何解决这一问题。

请帮助!

最佳回答

Recursion!

import java.util.HashMap;
import java.util.Map;

public class Chain
{
    private static Map< String , String > map;

    public static void main( String args[] )
    {
        map = new HashMap< String , String >();

        map.put( "1" , "2" );
        map.put( "3" , "4" );
        map.put( "2" , "3" );
        map.put( "6" , "2" );

        for ( String key : map.keySet() )
        {
            System.out.print( "(" + key + "," + map.get( key ) + ")" );
            recurse( map.get( key ) );
            System.out.println();
        }
    }

    private static void recurse( String value )
    {
        if ( map.containsKey( value ) )
        {
            System.out.print( " (" + value + "," + map.get( value ) + ")" );
            recurse( map.get( value ) );
        }
    }
}

取得以下成果:

(3,4)
(2,3) (3,4)
(1,2) (2,3) (3,4)
(6,2) (2,3) (3,4)
问题回答

创建<代码>Map<Integer, List<Integer>>,将所有奶制品储存在地图上,然后将地图上。

缩略语:

// 1st step
foreach(key, value){
    if(!map.containsKey(key)){
        map.put(key, new ArrayList());
    }
    map.get(key).add(value);
}
// 2nd step
foreach(entry /* of map */){
    if(map.containsKey(entry.value)){
       // print pairs
    }
}

显然,这只是一些精彩的代码,它赢得汇编,但应该让你开始。

既然这样看家事,我将给你帮助你解决问题,而不是给你一个完整的解决办法。

  1. For any key in the map, you can get the corresponding value by calling Map.get(key).
  2. You can use any value as a key to get its corresponding value (if there is one).
  3. You can iterate through all keys in the map using Map.getKeys().

如果你只想勾销链条,就足够了。 如果你想要将链存放在不同的数据结构中,请提供更多信息。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签