java将单个数字流转换为范围

use*_*410 6 java java-8 java-stream

我想将数字对转换为一系列整数,以便我可以对它们执行函数.例如,以下每一行:

1-4
5-6
1-2
4-7
Run Code Online (Sandbox Code Playgroud)

应转换为数组,即:[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()));
Run Code Online (Sandbox Code Playgroud)

ern*_*t_k 4

以下管道将 上的每一行分割-,然后用于IntStream在两者之间创建一个数字范围。

结果是所有这些内部整数的扁平流,后跟一个计数组(数字)。然后在此地图的值上找到最大“计数”。

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);
Run Code Online (Sandbox Code Playgroud)

使用您的示例数据,它会打印1=21找到两次)-有许多值正好找到两次。

  • 不需要 `.map(array -&gt; IntStream.rangeClosed(array[0], array[1])) .flatMapToInt(Function.identity())`。只需使用`.flatMapToInt(array -&gt; IntStream.rangeClosed(array[0], array[1]))` (3认同)