0

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).

HMNNikoloz
  • 29
  • 6
  • What programming language are you using? Is it javascript? – Mirek Pluta Nov 26 '21 at 21:07
  • Do you want to display the key or the value that appears the most? Keys can only appear once in maps. – fluffyyboii Nov 26 '21 at 21:10
  • 2
    Does this answer your question? [Using Java8 Stream to find the highest values from map](https://stackoverflow.com/questions/42060294/using-java8-stream-to-find-the-highest-values-from-map) – hfontanez Nov 26 '21 at 21:24

2 Answers2

3

You can find the max key using streams like this:

Character maxKey = map.entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .get().getKey();
csalmhof
  • 1,820
  • 2
  • 15
  • 24
1

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()

WJS
  • 36,363
  • 4
  • 24
  • 39