What you want is a multimap, a map that can have more than one value for each key, since you can have multiple (descriptor, value) pairs for each category. There are multimaps in some third party Java libraries such as Guava, but you can emulate one with the standard Java collections by using a map to a list of values, such as a Map<String, List<Descriptor>>
, where a Descriptor
is a type that contains a (descriptor, value) pair.
The merge
method that was added to Map
in Java 8 is effective for building such a map.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Map;
public class Descriptor {
private final String descriptor;
private final int value;
public Descriptor(String descriptor, int value) {
this.descriptor = Objects.requireNonNull(descriptor);
this.value = value;
}
public String getDescriptor() {
return descriptor;
}
public int getValue() {
return value;
}
@Override public String toString() {
return descriptor + ", " + value;
}
public static void main(String[] args) {
// create map (essentially a multimap
Map<String, List<Descriptor>> map = new HashMap<>();
insert(map, "Computers", "Keyboard", 10);
insert(map, "Computers", "Mouse", 5);
insert(map, "Cars", "Lamborghini", 6);
insert(map, "Cars", "BMW", 3);
// display all descriptors for a category
String category = "Cars";
for (Descriptor desc : map.get(category)) {
System.out.println(category + ", " + desc);
}
}
public static void insert(Map<String, List<Descriptor>> map,
String category, String descriptor, int value) {
// insert items in the map using Map.merge
List<Descriptor> list = new ArrayList<>();
list.add(new Descriptor(descriptor, value));
map.merge(category, list, Descriptor::concat);
}
public static List<Descriptor> concat(List<Descriptor> one,
List<Descriptor> two) {
one.addAll(two);
return one;
}
}
I assume that you can handle reading and parsing the input file yourself, or that you intent to work that out separately, since your question specifically asks about "HashMap help" and says that you have a problem using HashMap to solve this problem.