首页 > 解决方案 > 如何从 Intstream 创建 ArrayList

问题描述

所以我想将Person放入一个数组列表,但我需要使用流我有 csv 文件,它给我 infomartions id;name;sex 和一种使用那里的 id 将这些转换为Person对象的方法,

private Person readCSVLines(int id);

但我想创建一种方法,给我一个数组列表,我知道有 807 id 并且不会再有

我使用 toMap 尝试了这个,但它给了我一张地图,但我只想要一个 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
                    )
            );
        }
    }

标签: javaarraylistjava-stream

解决方案


在您的情况下,您只需使用 遍历所有行IntStream.range(from, to)并将每个行号转换为从 csv 读取的对象.mapToObj()。在这种情况下使用boxed()函数是多余的。最后,你需要的是

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

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


推荐阅读