有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

字典Java 8,整数流,按整数对流的索引进行分组?

我得到了一个整数流,我想根据每个元素的值对元素的索引进行分组
例如,{1, 1, 1, 2, 3, 3, 4}被分组为整数,以映射索引列表:

1 -> 0, 1, 2
2 -> 3
3 -> 4, 5
4 -> 6

我尝试过使用stream,但使用了一个额外的类:

@Test
public void testGrouping() throws Exception {
    // actually it is being read from a disk file
    Stream<Integer> nums = Stream.of(1, 1, 1, 2, 3, 3, 4);  
    // list to map by index
    int[] ind = {0};  // capture array, effectively final
    class Pair {
        int left;
        int right;

        public Pair(int left, int right) {
            this.left = left;
            this.right = right;
        }
    }

    Map<Integer, List<Integer>> map = nums.map(e -> new Pair(ind[0]++, e))
            .collect(Collectors.groupingBy(e -> e.right))
            .entrySet().parallelStream()
            .collect(Collectors.toConcurrentMap(
                    Map.Entry::getKey,
                    e -> e.getValue().parallelStream().map(ee -> ee.left).collect(Collectors.toList())
            ));
}

我必须读取流,因为整数流是从应用程序中的磁盘文件读取的
我觉得我这样做的方式是相当次优的。有更好或更优雅的方法吗
谢谢你的帮助


共 (0) 个答案