Reputation: 1046
I've looked to find that initializing a java EnumMap is possible with value of another HashMap but this is with testing. I'm not in need of using an efficient double bracket or anything like that I just need to create the map from a given map.
public EnumMap<ITEMS, Map<String, Double>> getPromotionItems(String state, Map<String, Double> prices) {
EnumMap<ITEMS, Map<String, Double>> promoItems = new EnumMap<>(ITEMS.class);
Iterator iterator = prices.entrySet().iterator();
Iterator keys = prices.keySet().iterator();
HashMap map = new HashMap<String, Double>();
while(keys.hasNext()) {
map.put(iterator.next(),keys.next());
}
promoItems.put(ITEMS.valueOf(state),map);
return promoItems;
}
I'm writing in Junit and this says that my iterators are wrong somehow
java.lang.AssertionError: expected: java.util.EnumMap<{ORIGINAL={ProductC=3.0, ProductA=1.0, ProductB=2.0}}> but was: java.util.EnumMap<{ORIGINAL={ProductC=3.0, ProductA=1.0, ProductB=2.0}}>
SOLUTION I needed to use only one enumMap in my class and unit test calling the method using the test class enumMap.
This was in my test class: TestClassForItems.java public enum ITEMS { ONPROMO, ORIGINAL, OFFPROMO }
@Test
public void onRedLinePromotionListOriginalPriceTest() {
testPromoState = "ORIGINAL";
testPrices.put("Product_A", 1.00);
testPrices.put("Product_B", 2.00);
testPrices.put("Product_C", 3.00);
expectedPrices = testPrices;
expectedGoodsMap.put(TestClassForItems.ITEMS.ORIGINAL, testPrices);
assertSame(expectedGoodsMap, TestClass.getPromotionItems(TestClassForItems.ITEMS.ORIGINAL,testPrices));
}
Returning the same String result but different object usage due to instantiating from the main for all of the necessary attributes to run my Junit test.
Upvotes: 1
Views: 1423
Reputation: 425043
Change:
assertSame
To:
assertEquals
assertSame()
is the same as ==
, whereas assertEquals()
does an equals()
compare.
Upvotes: 1
Reputation: 5048
A short solution:
public EnumMap<ITEMS, Map<String, Double>> getPromotionItems(String state, Map<String, Double> prices) {
EnumMap<ITEMS, Map<String, Double>> promoItems = new EnumMap<>(ITEMS.class);
promoItems.put(ITEMS.valueOf(state), new HashMap<>(prices));
return promoItems;
}
You have confused the data types. You are using a Entry as a String. If you define the data type with the right generic value, you'll get a compile error:
public EnumMap<ITEMS, Map<String, Double>> getPromotionItems(String state, Map<String, Double> prices) {
EnumMap<ITEMS, Map<String, Double>> promoItems = new EnumMap<>(ITEMS.class);
Iterator<Entry<String, Double>> iterator = prices.entrySet().iterator();
Iterator<String> keys = prices.keySet().iterator();
HashMap<String, Double> map = new HashMap<String, Double>();
while (keys.hasNext()) {
map.put(iterator.next(), keys.next());
}
promoItems.put(ITEMS.valueOf(state), map);
return promoItems;
}
Upvotes: 2