简体   繁体   中英

Using multiple HashMaps to retrieve values in Java

Consider two HashMap s. The first one contains the product name and product category code as key and value respectively. The second HashMap contains the product name and the units sold. I need to write a Java function which accepts the two hash maps and return the names of products in each category which is having the highest number of units sold.

Input1 :{“lux”:”soap”,”colgate”:”paste”, ”pears”:”soap”,”sony”:”electronics”,”samsung”:”electronics”}
Input 2:{“lux”:1000,”colgate”:500,”pears”:2000,”sony”:100,” samsung”,600}
Output: {“pears”,”colgate”,”samsung”}

Basically, I'll hold a map with from the category to the most popular item and its counter. You can either do this with two separate Map s, jimmy up a quick and dirty class to hold the info, or use something like Apache Commons Lang's Pair class . Without relying on any third party, I'd just define a simple class like this:

public class Item {
    String name;
    int amount;

    // constructor from name, amount

    // getters and setters
}

Now, you can iterate over the sales map and just save the most popular item for each category:

public Set<String> getPopularItems
    (Map<String, String> itemCategories, 
     Map<String, Integer> itemSales) {

    Map<String, Item> result = new HashMap<String, Item();

    for (Map.Entry<String, Integer> salesEntry: itemSales) {
        String itemName = itemSales.getKey();
        int itemAmount = itemSales.getValue();

        String category = itemCategories.get(itemName);

        if (result.contiansKey(category)) {
            int currAmount = result.get(category).getAmount();
            if (itemAmount > currAmount) {
                result.put (category, new Item (itemName, itemAmount));
            }
        } else {
            result.put (category, new Item (itemName, itemAmount));
        }
    }

    return result.keySet();
}

Note that this is a simplified implementation that does not deal with malformed inputs (eg, a category that appears in one map but not the other), or with edge cases (eg, two items with the same amount of sales). This is done for clarity's sake - I'm sure you could add these on later if needed.

@Arjun: answer code is given below :

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MultipleHashMapAccessDemo {

    protected Map<String, String> getProductCategoryMap() {
        Map<String, String> productCategoryMap = new HashMap<String, String>();

        productCategoryMap.put("Lux", "Soap");
        productCategoryMap.put("Pears", "Soap");
        productCategoryMap.put("Dove", "Soap");
        productCategoryMap.put("Colgate", "Paste");
        productCategoryMap.put("Babul", "Paste");
        productCategoryMap.put("Vico", "Paste");

        return productCategoryMap;
    }

    protected Map<String, Integer> getProductUnitsSoldMap() {
        Map<String, Integer> productUnitsSoldMap = new HashMap<String, Integer>();

        productUnitsSoldMap.put("Lux", 1000);
        productUnitsSoldMap.put("Pears", 3000);
        productUnitsSoldMap.put("Dove", 3010);
        productUnitsSoldMap.put("Colgate", 50);
        productUnitsSoldMap.put("Babul", 45);
        productUnitsSoldMap.put("Vico", 80);

        return productUnitsSoldMap;
    }

    protected Map<String, String> getExpectedProductCategoryMap(
            Map<String, String> productCategoryMap,
            Map<String, Integer> productUnitsSoldMap) {

        Map<String, String> expectedProductCategoryMap = new HashMap<String, String>();
        Set<String> categortSet = new HashSet<String>();

        Iterator iterator = productCategoryMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> mEntry = (Map.Entry) iterator.next();
            categortSet.add(mEntry.getValue());
        }

        for (String category : categortSet) {
            int tempUnits = 0;
            String desiredProductName = null;

            for (Object object : productUnitsSoldMap.entrySet()) {
                Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) object;

                String product = entry.getKey();
                if (category.equals(productCategoryMap.get(product))) {
                    if (tempUnits < entry.getValue()) {
                        tempUnits = entry.getValue();
                        desiredProductName = product;
                    }
                }
            }
            expectedProductCategoryMap.put(category, desiredProductName);
        }
        return expectedProductCategoryMap;
    }

    public static void main(String... strings) {

        MultipleHashMapAccessDemo accessDemo = new MultipleHashMapAccessDemo();
        Map<String, String> productCategoryMap = accessDemo
                .getProductCategoryMap();
        Map<String, Integer> productUnitsSoldMap = accessDemo
                .getProductUnitsSoldMap();

        Map<String, String> expectedProductCategoryMap = accessDemo
                .getExpectedProductCategoryMap(productCategoryMap,
                        productUnitsSoldMap);

        for (Object object : expectedProductCategoryMap.entrySet()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) object;

            System.out.print("Category name is : " + entry.getValue());
            System.out.println(" And Product name is : " + entry.getKey());
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM