Home > database >  Java - Displaying key in map with most occurrences - Java
Java - Displaying key in map with most occurrences - Java

Time:11-27

I have a string and i created a map which schows occurrences of characters:

String: "aaa bbbb ccccccccccc ddddd eeee"
map: {a=3, b=4, c=11, d=5, e=4}

And i want to display only c, also output:

c

(because it occurres most of the times).

CodePudding user response:

You can find the max key using streams like this:

Character maxKey = map.entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .get().getKey();

CodePudding user response:

There are many ways. Here is how I would do it.

Assuming your keys are strings.

  • stream the entry set.
  • get the max using the Entry comparator for value.
  • get the Entry of the optional and then get the string.
Map<String, Integer> maps = Map.of("c", 11, "d", 17, "f", 12);
String key = maps.entrySet().stream()
        .max(Entry.comparingByValue())
        .get().getKey();
System.out.println(key);

prints

d

You can also combine the two operations and use the chars().stream() method.

  • stream the characters
  • map to a Character object.
  • and count the characters grouping by the character
  • stream the entry set as before
  • and return the character.
String str = "aaa bbbb ccccccccccc ddddd eeee";
char key = str.chars()
        .mapToObj(ch -> Character.valueOf((char) ch))
        .collect(Collectors.groupingBy(s -> s,
                Collectors.counting()))
        .entrySet().stream().max(Entry.comparingByValue())
        .get().getKey();

System.out.println(key);

In this case, prints

c

If you only want letters to be counted you can filter with Character.isLetter()

  • Related