简体   繁体   中英

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

I need to store data from file i have read, the data structure is: ip adress and id (1.10.186.214;2812432), and id can have multiple ip.

here is the code i use to read file. I use Treemap userdb to store information about users. Also i need another map to store id and 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();

I have decided to use Hashmap id as key and set of ip as value. Is this the right way? And if it is not, what are the other options?

You already have the User that the IP address belongs to I would suggest you use that as the key for your second data structure:

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

(I have used InetAddress here but you may already have a class for this?)

You can then look up or create the set of IP addresses for a given user and add the new entry:

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

Your code has a couple of other possible issues:

  1. You are splitting each line into four components but your example data only has two?

  2. You create a new user for every entry when you have stated that a user can have multiple IP addresses (which is the point of the second data structure). You want to check whether you already have the user in userdb first, ie:

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

(You could use the computeIfAbsent approach again here to simply the logic).

Your User class should correctly implement hashCode and equals if you decide to use it as the key. Alternative #1 just the user ID as the key. Alternative #2 move the Set<InetAddress> into the User class where it logically lives anyway.

Finally there's not much point splitting the line four times, it won't matter for this exercise I imagine but it's a good habit to get into: final String[] parts = line.split(";"); String ip = parts[0]; ... final String[] parts = line.split(";"); String ip = parts[0]; ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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