Count appeareance of first string in tuple in hasmap<Tuple<String, String>, Integer> and write as value

StackOverflow https://stackoverflow.com/questions/23471498

  •  15-07-2023
  •  | 
  •  

Question

Hej,

I have a HashMap of the form HashMap<Tuple<String, String>, Integer> where I want to count the appearance of the first String in the tuple and save it as value.

Is there an easy way to do that? Because for now I can only think of complicated ways where I have to iterate over the map multiple times.

So basically I know how I could do this, but I'm searching for an elegant, readable way to do this.

Example:

        Input: [(<Apple, today>, null), (<Peach, today>, null), (<Apple, yesterday>, null)]
        Output: [(<Apple, today>, 2), (<Peach, today>, 1), (<Apple, yesterday>, 2)]
Was it helpful?

Solution

My solution so far: (please comment if this is a good solution or not readable/elegant enough)

   public HashMap<Tuple<String, String>, Integer> countStuff (HashMap<Tuple<String, String>, Integer> stuffToBeCounted){

        HashMap<Tuple<String, String>, Integer> result = new HashMap<Tuple<String, String>, Integer>();
        HashMap<String, Integer> countedStuff = new HashMap<String, Integer>();

        for (Tuple<String, String> tuple : stuffToBeCounted.keySet()) {
           if(countedStuff.containsKey(tuple.v1())){
              Integer oldValue = countedStuff.get(tuple.v1());
              countedStuff.put(tuple.v1(), oldValue+1);
           }
           else{
              countedStuff.put(tuple.v1(), 1);
           }
        }

        for(Tuple<String, String> tuple : stuffToBeCounted.keySet()){
           result.put(tuple, countedStuff.get(tuple.v1()));
        }

        return result;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top