简体   繁体   中英

Using a Hashmap in Java is it possible to print out the amount of keys will a same value?

If i have a Hashmap with the exact same values but different keys is it possible to get these keys with the same values and print out the amount of keys that share this value and the value itself that is shared and to do so dynamically so without hard coding the values in an if statement? Example,

CODE

HashMap<String, String> map = new HashMap<>();

map.put("Order1"  " pending " );
map.put("Order2"  " cancelled " );
map.put("Order3"  " pending " );
map.put("Order4"  " fulfilled " );

Desired output

pending 2
cancelled 1
fulfilled 1

You can put your values into a Set to get uniques, then count occurrences of each element with Collections.frequency :

Set<String> singles = new HashSet<>(map.values());

for(String element : singles) {
    System.out.println(element + ": " + Collections.frequency(map.values(), element));
}

No, HashMap does not provide this capability out-of-the-box.

However, you could use two different approaches to achieve the goal:

A) If the number of orders in each state does not need to be checked that often, simply iterate over map.values() and count the amount of orders in each state

B) If the number of orders is very large, or state needs to be checked often, each time you add a new order or update its state, increment a counter for the new state and decrement the counter for the old state.

Another option is to map each value to a number. Here's one way to do so using streams:

public static <K, V> Map<V, Long> foo(Map<K, V> map) {
    return map.entrySet().stream()
            .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.counting()));
}

You could then print out the results like so:

Map<String, String> map = ...;
foo(map).forEach((k, v) -> System.out.printf("%s %d%n", k, v));

You could also modify it to know which keys were mapped to the same value.

public static <K, V> Map<V, List<K>> foo(Map<K, V> map) {
    return map.entrySet().stream().collect(Collectors.groupingBy(
            Map.Entry::getValue,
            Collectors.mapping(Map.Entry::getKey, Collectors.toList())
    ));
}

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