In this example we will read each line in a file and convert it to a java object. There are many libraries that provide very similar functionality but it gets pretty easy with the introduction to java 8 functional programming features. In the event java 8 isn't yet available in your environment, you could perform almost the exact same behavior using guava. The trivia game program provided us with a use case where we needed to read a file and parse each line into a Question object. We will walk you through the process we took to achieve this.
To get us started, lets take a look at the triva.txt file. Each high level element is separated by a pipe and there are three pieces: question, multiple choice answers and the answer itself. The multiple choice question is separated by a comma and the answer is a number representing the index of the possible answers. For example, having an answer of 2 would represent the second element in the possible answers.
Creating a Questions object
We will first create a POJO object that represents the higher level question. It will contain the question, possible answers and the answer to the question.
Creating java 8 function
Java 8 introduced functions which are commonly used to map from one object to another and is common when converting from an arraylist to a hashmap. In our case we have a string in which we want to convert it to a java object named Question.
There are a few things happening in the apply method. We will create a new Question object and then break the string apart and assign the elements to the properties of the Question. The overall line can be split on the pipe delimiter while the possible answers can be split on a comma. For each split operation we will use guava's splitter class trimming and removing empty strings.
Putting it together
Java 7 introduced the revamped Files api and java 8 introduce the ability to process a file as a stream. Combining these pieces we can read the file and process each line. Tying the mapLineToQuestion function we will convert each line to the Question object and then will convert the stream to arraylist.