有一个名为Person的类:
(IntelijIdea 下划线标出“a[0]”,并显示“期望数组类型,找到:lambda 参数”)
class Person {
private String id;
private String name;
private int age;
private int amount;
}
我使用外部文件的行创建了一个包含Person
的HashMap
:
001,aaa,23,1200
002,bbb,24,1300
003,ccc,25,1400
004,ddd,26,1500
Mainclass.java
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]))));
}
}
对于 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]))));
(IntelijIdea 下划线标出“a[0]”,并显示“期望数组类型,找到:lambda 参数”)
int
值时,使用Integer.parseInt
比使用Integer.valueOf
更可取,以避免不必要的装箱为Integer
对象,然后再进行拆箱。此外,我会在Person
类中添加一个static
工厂方法,例如Person.parse(String)
来执行转换。 - Holger