Search code examples
javadictionaryjava-8java-streamcollectors

Write "in another format" a default map <String,Integer> by default to Integer 0 and then based on condition count the occurrencies


I have a default map of key value given like that

 private Map<String, Integer> output = Stream.of(MyEnumCode.values())
        .collect(Collectors.toMap(e -> e.code, e -> 0));//default EN1:0,ENS:0..

Note my enum is in this format

public enum MyEnum{

EN1("EN1"), ENS("ENS"), ENT("ENT").....;

String code;

MyEnum(String code) {
    this.code = code;
}

After that there is a part of code witha switch statement that based on condition determines the MyEnumCodeValue and it is reiterated again to count the occurrencies of these enumvalues like that:

 output.merge(MyEnumCode.code, 1, Integer::sum); //-->outuput like EN1:3,ENS:1 (based on occurrencies)

so by default I read this enumcodes and collect them to a map to output by default by 0. is there another way to achieve the same result written in another way?

Thanks in advance!


Solution

  • You can avoid the first statement where you are adding all the enum values in the map.

    private Map<String, Integer> output = Stream.of(MyEnumCode.values())
            .collect(Collectors.toMap(e -> e.code, e -> 0));//default EN1:0,ENS:0..
    

    Instead of doing this, you can do something like this.

    private Map<String, Integer> output = new HashMap<>();
    

    and at the time of putting values in the map, you can use,

    output.put(enumKey, output.getOrDefault(enumKey, 1));
    

    But the output can be diff for both the maps. Like this map will contain only those keys that are having occurrence more then one.

    Update:

    private Map<String, Integer> output = Stream.of(MyEnumCode.values())
            .collect(Collectors.toMap(e -> e.code, e -> 0));
    //Some statements
    //....
    //....
    output.put(enumKey, output.getOrDefault(enumKey, 0) + 1);
    

    Here output map will be having occurrence of all the enum keys be it 0 or not 0.