Home > OS >  Have to display the number of times an element has been added in my map JAVA
Have to display the number of times an element has been added in my map JAVA

Time:08-25

I created a TreeMap with products, and i want to count the number of times they repeat themselves, but have no clue what to code. Any hints? (no code expecting, just suggestions)

private static Map<Integer, String> shoppingCart(){
    Map<Integer, String> result = new TreeMap<>();
           result.put(1, "sausage");
           result.put(2, "sausage");
           result.put(3, "soup");
           result.put(4, "egg");
           result.put(5, "egg");
           result.put(6, "tomato");
           result.put(7, "sausage");
          
         return result;
       }
 

Was thinking about adding a counting variable, but still it doesn't fix the repeating problem

CodePudding user response:

Maybe not the best approach, but without modifying what you already have, you could use another map to store the products as keys and the count as the value for those keys:

Map<Integer, String> result = shoppingCart();
Map<String, Integer> productQuantities = new HashMap<>();

result.keySet().forEach(key ->{
    String resultMapValue = result.get(key);
    if(!productQuantities.containsKey(result.get(key))) {
        productQuantities.put(result.get(key), 1);
    } else {
        productQuantities.put(result.get(key), productQuantities.get(result.get(key)) 1);
    }
});

To print the resulting map:

productQuantities.entrySet().forEach(entry ->{
    System.out.println(entry.getKey()   ":"   entry.getValue().toString());
});

CodePudding user response:

I created a TreeMap with products, and i want to count the number of times they repeat themselves

Probably a different type of Map with keys representing items and values representing the corresponding count would be more handy. Something like:

NavigableMap<String, Integer> countByItem

Note: in order to access methods of the TreeMap like ceilingKey(), floorKey(), higherEntry(), lowerEntry(), etc. which are not defined in the Map interface you need to use NavigableMap as a type.

And it might make sense to make the item to be a custom object, instead of being a String. That would guard you from making typo, and it provides a possibility to gives useful behavior to Item

public class Item {
    private int id;
    private String name;
    
    // constructor, getters, equals/hashCode, ect.
}

That's how map of items can be updated using Java 8 method merge(), which expects a key, a value and a function responsible for merging the old value and the new one:

NavigableMap<Item, Integer> countByItem = new TreeMap<>(Comparator.comparingInt(Item::getId));
        
countByItem.merge(new Item(1, "sausage"),1, Integer::sum);
countByItem.merge(new Item(1, "sausage"),1, Integer::sum);
countByItem.merge(new Item(2, "soup"),1, Integer::sum);

If you don't feel very comfortable with Java 8 functions, instead of merge() you can use combination of methods put() & getOrDefault():

Item sausage = new Item(1, "sausage");

countByItem.put(sausage, countByItem.getOrDefault(sausage, 0)   1);
  • Related