Search code examples
javajava-stream

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 have created HashMap of Person 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 ArrayList?

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 expected,found : lambda parameter")


Solution

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