简体   繁体   English

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

[英]How to Create A HashMap using Key Values from a text file?

I have to create a hashmap with the names I have in this text file 我必须使用此文本文件中的名称创建一个哈希图

relationships text file: 关系文本文件:

 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 

This is the program I have now: 这是我现在拥有的程序:

 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); } 

This is the output: 这是输出:

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

Does anyone know how to fix this please? 有谁知道如何解决这个问题? Also how to seperate them so it actually looks like a list? 以及如何分隔它们,使其看起来像一个列表?

EDIT 编辑

I think you would just change your line: 我认为您只需要更改行即可:

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

to: 至:

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

Then column[0] would be the name on the left, and column[1] would be the name and movie title on the right. 然后column[0]将是左侧的名称,而column[1]将是右侧的名称和电影标题。

Note that you'll need to import java.util.regex.Pattern; 注意,您需要import java.util.regex.Pattern; to do this 去做这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM