Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream API collect method

There is class Person:

class Person {
    private String id;
    private String name;
    private int age;
    private int amount;
}

and I create HashMap of Persons 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")

like image 395
harp1814 Avatar asked Dec 06 '22 09:12

harp1814


2 Answers

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).

like image 144
Eran Avatar answered Dec 26 '22 07:12

Eran


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())
like image 42
Naman Avatar answered Dec 26 '22 05:12

Naman