我想将数字对转换为整数范围,以便对它们执行函数。 例如每一行:
1-4
5-6
1-2
4-7
应转换为数组,即:[1,2,3,4]。 我的目标是计算出现频率最高的数字。 我正在尝试像字数统计示例那样做,但问题是如何从每行中的两个数字创建范围流?
Path path = Paths.get(args[0]);
Map<String, Long> wordCount = Files.lines(path)
.flatMap(line -> Arrays.stream(line.trim().split("-")))
.
.map(word -> word.replaceAll("[^a-zA-Z]", "").toLowerCase().trim())
.filter(num -> num.length() > 0)
.map(number -> new SimpleEntry<>(number, 1))
.collect(Collectors.groupingBy(SimpleEntry::getKey, Collectors.counting()));
最佳答案
以下管道在 -
上拆分每一行,然后使用 IntStream
创建两者之间的数字范围。
结果是所有这些内部整数的扁平化流,后跟按(数字)的计数组。然后在此 map 的值上找到最大“计数”。
String s = "1-4\n" + "5-6\n" + "1-2\n" + "4-7"; //simpler version with inline text
Optional<Entry<Integer, Long>> result =
Stream.of(s.split("\n")) //replace with Files.lines(path) for real stream
.map(line -> line.split("-"))
.map(array -> new int[] { Integer.parseInt(array[0].trim()),
Integer.parseInt(array[1].trim()) })
.map(array -> IntStream.rangeClosed(array[0], array[1]))
.flatMapToInt(Function.identity())
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparingLong(Entry::getValue));
result.ifPresent(System.out::println);
使用您的示例数据,它会打印 1=2
(1
找到了 2 次)- 有很多值恰好找到了两次。
关于java将单个数字流式传输到一个范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52430539/