2

i have a List with Strings and group the same Strings.

List<String> allTypes = new ArrayList<String>();

Map<String, Long> count = allTypes.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

and then i get the count of the most frequent String

Long max = Collections.max(count.values());

Now i dont want only the count of the most frequent String i want the associated String too. The List is randomly filled with Strings from a other List.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Swipi
  • 27
  • 4

2 Answers2

5

I think you are looking to:

Optional<Map.Entry<String, Long>> maxEntryByValue = count.entrySet()
        .stream()
        .max(Comparator.comparing(Map.Entry::getValue));

Or if you want it without Optional, you can use:

Map.Entry<String, Long> maxEntryByValue = count.entrySet()
        .stream()
        .max(Comparator.comparing(Map.Entry::getValue))
        .orElse(null); // or any default value, or you can use orElseThrow(..)
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • The `max` call can be written more succinctly as `max(Map.Entry::comparingByValue)`. – VGR Oct 15 '20 at 16:00
  • 1
    You should probably mention that in case that 2 Strings (keys) have the same count, only one entry will be returned. In case the requirement would be to return multiple map entries if the maximum isn't a unique value i guess you could do that with something like `List> maxEntries = count.entrySet().stream().filter(x -> x.getValue().equals(Collections.max(count.values()))).collect(Collectors.toList());` (Probably not very effective, just my first idea) – OH GOD SPIDERS Oct 15 '20 at 16:02
  • @VGR I tried your solution in side but it *Cannot resolve method 'comparingByValue'* – Youcef LAIDANI Oct 15 '20 at 16:05
  • @OHGODSPIDERS yes, I agree, if the OP wait a multiple value, then he/she should follow another approach. – Youcef LAIDANI Oct 15 '20 at 16:06
  • @YCF_L [It should be there.](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/Map.Entry.html#comparingByValue()) – VGR Oct 15 '20 at 16:22
  • what I have to do if i just want the string for example "stackStr" not like "stackStr=201" – Swipi Oct 19 '20 at 14:18
  • @Swipi do you mean `maxEntryByValue.getKey()` ? – Youcef LAIDANI Oct 19 '20 at 14:26
  • Yes thank you !!! Thank You for your help! – Swipi Oct 19 '20 at 15:26
0

You can iterate over the entries and if the value matches your targetValue then store that key in the Set<K> keys. This will contain all the keys having that particular targetValue

    for (Map.Entry<String, Object> entry : map.entrySet()) {
      String key = entry.getKey();
      Object value = entry.getValue();
      if (value.equals(targetValue)) {
        keys.add(entry.getKey());//add the keys to the set<K> keys
      }
    }
    return keys; //all the keys having the same targetValue will be in this set
p_flame
  • 102
  • 6