繁体   English   中英

如何将我从文件中读取的数据放入哈希图<String, Set<String> &gt;?

[英]How to put data i read from file to hashmap <String, Set<String>>?

我需要存储我读过的文件中的数据,数据结构是:ip地址和id(1.10.186.214;2812432),id可以有多个ip。

这是我用来读取文件的代码。 我使用 Treemap userdb 来存储有关用户的信息。 我还需要另一个地图来存储 id 和 ip。

File file = new File(path);
        Scanner scanner = new Scanner(file);
        Map<String, User> userdb = new TreeMap<>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String ip = line.split(";")[0];
            String id = line.split(";")[1];
            String fio = line.split(";")[2];
            String adress = line.split(";")[3];
            User user = new User(id, fio, adress);
            userdb.put(id, user);
        }
        scanner.close();

我决定使用 Hashmap id 作为键,使用一组 ip 作为值。 这是正确的方法吗? 如果不是,还有什么其他选择?

您已经拥有 IP 地址所属的User ,我建议您将其用作第二个数据结构的键:

Map<User, Set<InetAddress>> mappings = new HashMap<>();

(我在这里使用了InetAddress ,但您可能已经有一个用于此的类?)

然后,您可以查找或创建给定用户的 IP 地址集并添加新条目:

InetAddress address = InetAddress.getByName(ip);
mappings.computeIfAbsent(user, ignored -> new HashSet<>()).add(address);

您的代码还有其他几个可能的问题:

  1. 您将每一行分成四个部分,但您的示例数据只有两个?

  2. 当您声明一个用户可以拥有多个 IP 地址(这是第二个数据结构的点)时,您将为每个条目创建一个用户。 您要先检查userdb是否已经有该用户,即:

        final User user;
        if(users.containsKey(id)) {
            user = users.get(id);
        }
        else {
            user = new User(id);
            users.put(id, user);
        }

(您可以在computeIfAbsent再次使用computeIfAbsent方法来简化逻辑)。

如果您决定使用它作为键,您的User类应该正确实现hashCodeequals 替代方案 #1 只是用户 ID 作为密钥。 备选方案#2 将Set<InetAddress>移动到它逻辑上无论如何都存在的User类中。

最后,将线分割四次没什么意义,我想这对这个练习来说无关紧要,但养成一个好习惯: final String[] parts = line.split(";"); String ip = parts[0]; ... final String[] parts = line.split(";"); String ip = parts[0]; ...

暂无
暂无

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

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