Raviga
Raviga

Reputation: 129

What would be the best data structure to use? java

I have a GUI where people can enter data and I'm not sure what the best way to store the data would be. This is how I would visualize the data:

Cats: Cheetah, lion, puma
Dogs: husky, lab

The user could add a type of animal, like a fox, and then add types of foxes. They could also add new types of cats and dogs to the existing lists of them. What would be the best data-structure to use to store this?

Upvotes: 0

Views: 135

Answers (4)

Amir Afghani
Amir Afghani

Reputation: 38561

You can use Guava's MultiMap to manage something like:

Map<Key, CollectionOfValues>

I would think about the data model a bit more and see if you can create a wrapper class for the members of each group. This will make the code more readable in the long run. Perhaps:

Map<Genus, Members>

Upvotes: 0

Paul Boddington
Paul Boddington

Reputation: 37655

You could use a HashMap<String, Set<String>>.

Example:

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

// To add a new category of animal
animals.put("Cat", new HashSet<>());
animals.put("Dog", new HashSet<>());

// To add a new animal to an existing category
animals.get("Cat").add("Puma");
animals.get("Cat").add("Tiger");
animals.get("Dog").add("Labrador");

// prints {Cat=[Tiger, Puma], Dog=[Labrador]}
System.out.println(animals);

Upvotes: 0

erickson
erickson

Reputation: 269857

Map<Family,Set<Species>>

For concrete classes, I might use TreeMap and TreeSet, making sure that my Family and Species types implement comparable (or these types could be replaced by String). These types are sorted, so iterating over them would display data in a sensible order.

Upvotes: 1

Abhishek Vasisht
Abhishek Vasisht

Reputation: 426

You could simply use a

HashMap<String,ArrayList<String>> container

Where the first String refers to the animal type name and the arraylist holds animal names under that type.

Upvotes: 0

Related Questions