如何在不同集合的集合中创建对象流

How to create a stream of objects inside a collection of a different collection

我正在创建一个数组的 ArrayList,然后从方法中以 Stream 的形式返回数据。但是我需要数组中的对象流。我相信我需要使用 但我所拥有的对我不起作用,而当我 return Stream.of(Arguments.of(kt,r,expectedPoints)); 它起作用时,我在单元测试中正确地看到了对象。

class KdTreeTest {
    static class KdTreeArgumentsProvider implements ArgumentsProvider {
        final static File folder = new File("src/main/resources/kdtests/");
        KdTree kt = new KdTree();
        RectHV r = new RectHV(0.1, 0.1, 0.5, 0.6);
        Point2D p1 = new Point2D(0.1, 0.2);
        Point2D p2 = new Point2D(0.8, 0.9);
        Point2D[] expectedPoints = {p1, p2};

        @Override
        public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) throws Exception {
            Object[] instanceData = new Object[3];
            List<Object> l = new ArrayList<>();
            for (final File fileEntry : folder.listFiles()) {
                String fileName = fileEntry.getName().toUpperCase();
                if (fileName.endsWith(".TXT")) {
                    Scanner scanner = new Scanner(fileEntry);
                    kt = new KdTree();
                    while (scanner.hasNext()) {
                        double x = scanner.nextDouble();
                        double y = scanner.nextDouble();
                        Point2D p = new Point2D(x, y);
                        kt.insert(p);
                    }
                    instanceData[0] = kt;
                    instanceData[1] = r;
                    instanceData[2] = expectedPoints;
                    l.add(instanceData);
                }
            }
            return Stream.of(Arguments.of((l.stream().flatMap(x->Stream.of("x[0]","x[1]","x[2]")))));
        }
    }

    @DisplayName("should create a rectangle with the given coordinates and test KdTree's range() function")
    @ParameterizedTest(name = "{index}=> kt={0},r={1},expectedPoints={2}")
    @ArgumentsSource(KdTreeArgumentsProvider.class)
    void range(KdTree kt, RectHV r, Point2D[] expectedPoints) {
        Assertions.assertNotNull(kt.range(r));
    }
}

我想我可以从一开始就把所有东西都放在一个 Object[] 中,但我们的好奇心是有没有办法用 Stream 方法做到这一点?

如果我没有正确理解您要执行的操作,那么您需要进行两项更改:

  1. l 的类型从 List<Object> 更改为 List<Object[]>:

    List<Object[]> l = new ArrayList<>();
    
  2. 将return语句改为:

    return l.stream()
            .map(Arguments::of);
    

打开包装:

  1. l.streaml
  2. 生成 Stream<Object[]>
  3. map(Arguments::of) 在流中的每个数组上调用 Arguments.of,创建一个包含三个条目的 Arguments 对象,匹配 range 方法的参数

您不想将数组展平到流中,因为这会导致 Arguments 个对象的流只有一个元素。