Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 176
  • Last Modified:

Collection ...

Hello experts,

   I have the following file:
--------------------------
  Animal, Type
 
  turtle, reptile
  lizard, reptile
  snake, reptile
  dog, mammal
  cat, mammal
  rat, mammal
 shark, fish
 goldfish, fish
----------------------

   I want them in a structure like:
 
   reptile : turtle, lizard, snake
   mammal: dog, cat, rat
   fish : shark, goldfish

  What type of collection and structure should I use to solve this problem ? thanks.
 
0
meow00
Asked:
meow00
  • 2
1 Solution
 
Jim CakalicSenior Developer/ArchitectCommented:
I'd probably approach this using a Map of Lists. You'd have a Map keyed by animal genus (or whatever it is) where the value of the map was a List which contained the species. Something like:

    Map genus = new HashMap();
    for each line in the file
        String split = line.split(",");
        List species = genus.get(split[0]);
        if (species == null) {
            species = new ArrayList();
            genus.put(split[0], species);
        }
        species.add(split[1]);

Regards,
Jim


0
 
Jim CakalicSenior Developer/ArchitectCommented:
Hi, meow00. Did my comment answer your question?
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now