gpt4 book ai didi

java - 在 Java 中从文本文件创建数据结构

转载 作者:行者123 更新时间:2023-11-30 06:15:14 25 4
gpt4 key购买 nike

我有一个看起来像这样的文件:

User -> Artist
u1 -> a1
u1 -> a15
u1 -> a123
u2 -> a1
u2 -> a32
...
u1800 -> a56

它告诉我们每个用户都听过哪些艺术家。

我如何将其导入二维数组(或者另一个更合适的数据结构?),其中每一行都是一个用户,每一 [行] [列] 是用户听过的一位艺术家?

我想最终存储 u1 已经听过 {a1, a15, a123} etc

最佳答案

您可以将此信息存储在 Map 中.假设你有一个 User类和一个 Artist类,你可以创建一个 Map<User, Set<Artist>>这将为每个用户保留一组(如果您愿意,也可以是列表)艺术家。

要创建您要执行的 map :

Map<User, Set<Artist>> artistsFromUser = new HashMap<>();

如果您只需要将用户名和艺术家姓名存储为字符串,您的 map 可以是:

Map<String, Set<String>> artistsFromUser = new HashMap<>();

然后您需要遍历您的文件,转换每个 user -> artist配对成 user对象和 artist目的。之后,您可以存储 artist使用相应的 user引用:

// Retrieve the set of artists for this user
// Substitute String for Artist here if you're just storing the names
Set<Artist> artists = artistsFromUser.get(user);
if (artists == null) {
// If the set was not created for this user yet
// you need to create it and store it in the map
artists = new HashSet<>();
artistsFromUser.put(user, artists);
}
// Add the new artist to the set
artists.add(artist);

打印输出就像这样做一样简单:

System.out.println(user + " has listened to " + artistsFromUser.get(user));

关于java - 在 Java 中从文本文件创建数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29155787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com