There is class Person:
class Person {
private String id;
private String name;
private int age;
private int amount;
}
and I create HashMap
of Person
s using external file contains lines:
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]))));
}
}
}
It works fine for HashMap
.
How to do the same for ArraList
?
I tried:
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 is underlined in red "a[0]" and says "Array type excpected,found : lambda parameter")
You should use map
in order to map each array to a corresponding Person
instance:
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());
BTW, Collectors.toList()
returns a List
, not an ArrayList
(even if the default implementation does return ArrayList
, you can't count on that).
You need to map
it to the Person
object before trying to collect
it:
.map(s -> s.split(","))
.map(a -> new Person(a[0],a[1],Integer.valueOf(a[2]),Integer.valueOf(a[3])) //here
.collect(Collectors.toList())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With