Mapping String with delimiters to list of strings or to new object

Viewed 325

I have a file with some data separated by semicolon. I'm trying to build a stream, which will read file line by line, separate every column of data and map it to new object.

data.txt:

John;Smith;42;shopassistant
Clara;Lefleur;24;programmer

Person.class:

public class Person{
   String name;
   String lastName;
   int age;
   String job;
}

I started with something like this:

List<Person> people = Files.lines(Paths.get("src/data.txt"))....

Any ideas?

2 Answers

You can use map like so :

List<Person> people = Files.lines(Paths.get("src/data.txt"))
        .map(p -> p.split(";"))//split each line with ';'
        .map(p -> new Person(p[0], p[1], Integer.valueOf(p[2]), p[3]))//create a new Person
        .collect(Collectors.toList());//then collect the result

Make sure that you have a constructor which hold that information :

public Person(String name, String lastName, int age, String job) {

A Scanner would be more useful for this job, and since java-9 this is much nicer to work with:

Pattern p = Pattern.compile("^(\\w+);(\\w+);(\\w+);(\\w+)$", Pattern.MULTILINE);
List<Person> persons = new Scanner(Paths.get("src/data.txt"))
            .findAll(p)
            .map(mr -> new Person(mr.group(1), mr.group(2), Integer.valueOf(mr.group(3)), mr.group(4)))
            .collect(Collectors.toList());
Related