Если вы хотите увидеть все числа на максимальной частоте, это можно сделать так:
private static List<Integer> findMaxOccurs(String... ranges) {
return Optional
.ofNullable(
Arrays.stream(ranges)
.map(r -> r.split("-"))
.flatMap(r -> IntStream.rangeClosed(Integer.parseInt(r[0]),
Integer.parseInt(r[1]))
.boxed())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
// We now have Map<Integer, Long> mapping Number to Frequency
.entrySet()
.stream()
.collect(Collectors.groupingBy(Entry::getValue, TreeMap::new,
Collectors.mapping(Entry::getKey, Collectors.toList())))
// We now have TreeMap<Long, List<Integer>> mapping Frequency to Numbers
.lastEntry()
)
.map(Entry::getValue)
.orElse(Collections.emptyList());
}
Тест
System.out.println(findMaxOccurs("1-4", "5-6", "1-2", "4-7"));
Выход
[1, 2, 4, 5, 6]
Если вы хотите узнать частоту этих чисел, было бы лучше разделить ее на два метода:
private static Entry<Long, List<Integer>> findMaxOccurring(String... ranges) {
return Arrays.stream(ranges)
.map(r -> r.split("-"))
.flatMap(r -> IntStream.rangeClosed(Integer.parseInt(r[0]),
Integer.parseInt(r[1])).boxed())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
// We now have Map<Integer, Long> mapping Number to Frequency
.entrySet()
.stream()
.collect(Collectors.groupingBy(Entry::getValue, TreeMap::new,
Collectors.mapping(Entry::getKey, Collectors.toList())))
// We now have TreeMap<Long, List<Integer>> mapping Frequency to Numbers
.lastEntry();
}
private static List<Integer> findMaxOccurringNumbers(String... ranges) {
return Optional.ofNullable(findMaxOccurring(ranges))
.map(Entry::getValue)
.orElse(Collections.emptyList());
}
Тест
System.out.println(findMaxOccurring("1-4", "5-6", "1-2", "4-7"));
System.out.println(findMaxOccurringNumbers("1-4", "5-6", "1-2", "4-7"));
Выход
2=[1, 2, 4, 5, 6]
[1, 2, 4, 5, 6]