有 Java 编程相关的问题?

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

java Lambda输入文件到数组中

我正在完成作业的最后一部分,遇到了困难。我需要使用InputData类的stream方法将下面的代码转换为Lambda语句,以及与当前循环具有相同效果的forEach循环。对于stream方法,我正在考虑使用。。。输入数据。stream()。forEach(values->;…就在try块内,但我无法理解forEach循环的其余语法。有人能告诉我正确的方向吗?谢谢

private List<AreaData> readInput(String filename) throws IllegalStateException,
        NumberFormatException
{
    /* This statement uses the "diamond" operator, since it is possible for
       the compiler to work out the required generic type. */
    final List<AreaData> result = new LinkedList<>();
    try( InputData inputData =
            new InputData(filename, InputData.class, null,
                    Field.values().length, ",") )
    {
        /* Iterate through each of the lines of values. */
        for( String[] values : inputData )
        {
            /* Create a new AreaData object, and add it to the list. */
            AreaData next = new AreaData(values);

            result.add(next);
        }
    }
    return result;
}

共 (1) 个答案

  1. # 1 楼答案

    假设inputData.stream()返回一个Stream<String[]>,您可以使用流上的映射操作来实现这一点,而不是forEach方法。mapper函数将String[]作为参数,并将返回一个新的AreaData实例(您可以使用构造函数引用来缩短它)。下面是使用映射操作时代码的样子:

    private List<AreaData> readInput(String filename)  throws IllegalStateException, NumberFormatException {
        try(InputData inputData = new InputData(filename, 
                                                InputData.class, 
                                                null, 
                                                Field.values().length, ",")) {
            return inputData.stream().map(AreaData::new).collect(Collectors.toList());
        }
    }
    


    如果你必须使用forEach方法,你基本上要做的就是这样;对于inputData实例中的每个String数组,创建一个新的AreaData实例并将其添加到列表中(因此lambda将是values -> result.add ...)。但是我觉得这种方法有点奇怪。在我看来,映射操作是您在这里应该做的,因为它实际上是从一个新的AreaData实例到每个数组的映射。