Skip to content

Instantly share code, notes, and snippets.

@eleanor-em
Created May 7, 2019 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eleanor-em/b12a6c5ee4306e683208b082abb6c03d to your computer and use it in GitHub Desktop.
Save eleanor-em/b12a6c5ee4306e683208b082abb6c03d to your computer and use it in GitHub Desktop.
Example of using HashMap in Java.
import java.util.Arrays;
import java.util.HashMap;
class Ingredient {
public final String name;
public Ingredient(String name) {
this.name = name;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object other) {
if (other instanceof Ingredient) {
return name.equals(((Ingredient) other).name);
}
return false;
}
@Override
public String toString() {
return name;
}
}
class Recipe {
private Ingredient[] ingredients;
public Recipe(Ingredient[] ingredients) {
this.ingredients = ingredients;
}
public Ingredient[] getIngredients() {
return Arrays.copyOf(ingredients, ingredients.length);
}
}
class Main {
public static HashMap<Ingredient, Integer> generateDict(Recipe recipe) {
HashMap<Ingredient, Integer> map = new HashMap<>();
for (Ingredient ingredient : recipe.getIngredients()) {
map.putIfAbsent(ingredient, 0);
int count = map.get(ingredient);
map.put(ingredient, count + 1);
}
return map;
}
public static void main(String[] args) {
HashMap<Ingredient, Integer> map = generateDict(new Recipe(new Ingredient[] {
new Ingredient("apple"),
new Ingredient("apple"),
new Ingredient("butter"),
new Ingredient("cinnamon"),
new Ingredient("icing sugar"),
}));
System.out.println(map);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment