Created
May 7, 2019 05:23
-
-
Save eleanor-em/b12a6c5ee4306e683208b082abb6c03d to your computer and use it in GitHub Desktop.
Example of using HashMap in Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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