如何使用文本文件中的键值创建HashMap?

时间:2016-02-25 03:50:33

标签: java file hashmap

我必须使用此文本文件中的名称

创建一个hashmap

关系文本文件:



Susan Sarandon | Tom Hanks : Cloud Atlas
Tom Hanks | Kevin Bacon : Apollo 13
Leonardo Dicaprio | Kevin Bacon : This Boy's Life
Robert De Niro | Kevin Bacon : This Boy's Life
Barack Obama | Tom Hanks : the Road We've Traveled
Helen Keller | Katharine Cornell : Helen Keller in Her Story
Katharine Cornell | Helen Hayes : Stage Door Canteen
Helen Hayes | John Laughlin : Murder with Mirrors
John Laughlin | Kevin Bacon : Footloose
Mark Zuckerberg | Joe Lipari : Terms and Conditions May Apply
Joe Lipari | Welker White : Eat Pray Love
Welker White | Kevin Bacon : Lemon Sky




这是我现在的程序:



public static void main(String[] args)
	
			throws FileNotFoundException
	{
		Scanner input = new Scanner(new File("relationships"));
		HashMap<String, String> relationships = new HashMap<String, String>();
		
		while (input.hasNextLine()) {
            String[] columns = input.nextLine().split(" ");
            relationships.put(columns[0], columns[1]);
        }

        System.out.println(relationships);
    
		}
&#13;
&#13;
&#13;

这是输出:

&#13;
&#13;
{Leonardo=Dicaprio, Katharine=Cornell, Joe=Lipari, Tom=Hanks, Robert=De, Susan=Sarandon, John=Laughlin, Mark=Zuckerberg, Barack=Obama, Welker=White, Helen=Hayes}
&#13;
&#13;
&#13;

有人知道如何解决这个问题吗?另外如何分离它们实际上看起来像一个列表?

1 个答案:

答案 0 :(得分:0)

修改

我想你只会改变你的行:

String[] columns = input.nextLine().split(" ");

为:

String[] columns = input.nextLine().split(Pattern.quote(" | "));

然后column[0]将是左侧的名称,column[1]将是右侧的名称和电影标题。

请注意,您需要import java.util.regex.Pattern;才能执行此操作