Java Stream API收集方法

har*_*814 3 java java-stream

有班人:

class Person {
    private String id;
    private String name;
    private int age;
    private int amount;
}
Run Code Online (Sandbox Code Playgroud)

我使用外部文件创建了HashMapPerson其中包含以下行:

001,aaa,23,1200
002,bbb,24,1300
003,ccc,25,1400
004,ddd,26,1500
Run Code Online (Sandbox Code Playgroud)

主类

public class Mainclass {
public static void main(String[] args) throws IOException {
    List<Person> al = new ArrayList<>();
    Map<String,Person> hm = new HashMap<>();
    try (BufferedReader br = new BufferedReader(new FileReader("./person.txt"))) {
        hm = br.lines().map(s -> s.split(","))
                .collect(Collectors.toMap(a -> a[0], a-> new Person(a[0],a[1],Integer.valueOf(a[2]),Integer.valueOf(a[3]))));
    }
}
Run Code Online (Sandbox Code Playgroud)

}

它适用于HashMap

怎么做ArraList呢?

我试过了:

    al = br.lines().map(s -> s.split(","))
                    .collect(Collectors.toList(a -> new Person(a[0],a[1],Integer.valueOf(a[2]),Integer.valueOf(a[3]))));
Run Code Online (Sandbox Code Playgroud)

(IntelijIdea下划线为红色“ a [0]”,并表示“期望的数组类型,找到的是:lambda参数”)

Era*_*ran 10

您应该使用map为了将每个数组映射到相应的Person实例:

al = br.lines().map(s -> s.split(","))
               .map (a -> new Person(a[0],a[1],Integer.valueOf(a[2]),Integer.valueOf(a[3])))
               .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

顺便说一句,Collectors.toList()返回一个List,而不是ArrayList(即使默认实现确实返回ArrayList,您也不能指望)。