如何从 Intstream 创建一个 ArrayList

3

我希望将Person放入一个数组列表中,但需要使用流。 我有一个csv文件,提供以下信息: id;name;sex 还有一个方法,可以使用它们的id将其转换为Person对象。

private Person readCSVLines(int id);

但是我希望创建一个方法,给我所有它们的数组列表。我知道有807个ID,不会再多了。

我尝试使用toMap,但它只给了我一个map,而我只想要一个ArrayList:

public ArrayList<Person> getAllPerson() {
        try (IntStream stream = IntStream.range(1, personmax)) { // personmax is 807 here
            return stream.boxed().collect(
                    Collectors.toMap(
                            i -> i,
                            this::readCSVLines,
                            (i1, i2) -> {
                                throw new IllegalStateException();
                            },
                            ArrayList::new
                    )
            );
        }
    }
2个回答

3
在您的情况下,您只需要使用IntStream.range(from, to)迭代所有行,并利用.mapToObj()将每个行号转换为从CSV读取的对象。在这种情况下使用boxed()函数是冗余的。 最后,您所需要的是:
    public List<Person> getAllPerson() {
       return IntStream
            .range(1, personmax) // personmax is 807 here
            .mapToObj(this::readCSVLines)
            .collect(Collectors.toList());
       }
    }

此外,请注意您的方法应该将接口作为返回类型 (List),而不是具体实现 (ArrayList)。

2
无需使用toMap,您需要使用mapToObjcollect方法。示例如下:
public ArrayList<Person> getAllPerson() {
    return IntStream.range(1, personmax)
            .mapToObj(this::readCSVLines)
            .collect(Collectors.toCollection(ArrayList::new));
}

更好的方法是使用 List<Person> 而不是 ArrayList<Person>

public List<Person> getAllPerson() {
    return IntStream.range(1, personmax)
            .mapToObj(this::readCSVLines)
            .collect(Collectors.toList());
}

请注意,您无需将 IntStream.range 放在 try catch 块中。这是无用的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接