Вы можете решить вашу проблему в несколько этапов:
// Step 1: group by counting
Map<String, Long> grouping = substrings.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// Step 2: find the max value
Long maxValue = grouping.entrySet().stream()
.max(Map.Entry.comparingByValue())
.get()
.getValue();
// Step 2: filter the entry which have max value and then max length,
// In the end repeat your String maxValue time
return grouping.entrySet()
.stream()
.filter(entry -> entry.getValue() == maxValue)
.max(Map.Entry.comparingByKey(Comparator.comparingInt(String::length)))
.map(entry -> entry.getKey().repeat(maxValue.intValue()))
.get();
Я вас не понимаю, когда вы используете orElse("-1")
, я думаю, что это бесполезно, просто используйте get()
в конце, и если вы хотите избежать пустых строк, просто сделайте проверку в начале вашего метода:
if (str.isEmpty()) {
return "-1";
}
Примечание: я использовал repeat
, которые существуют в Java11, если вы используете старую версию, есть много способов повторить строку.
Или, как @ Holger , упомяните, вы сразу используете:
return substrings.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.<String, Long>comparingByValue().thenComparingInt(e -> e.getKey().length()))
.map(entry -> entry.getKey().repeat(entry.getValue().intValue()))
.get();