Say we have a text file that contains (product name, price)
pairs. Each pair occupies two lines in the text file where the first line corresponds to the product name, and the second line corresponds to the price of that product. We may assume the text file is in the right format (and has an even amount of lines)
Example:
Ice Cream
$3.99
Chocolate
$5.00
Nice Shoes
$84.95
...
Now I have a simple class representing such pairs:
public class Product {
private final String name;
private final int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return this.name;
}
public int getPrice() {
return this.price;
}
}
We read the file containing the pairs and now have a string array containing all the individual lines. I need to use Streams to map each two lines to one object of type Product
.
How can I group two lines each and then map them to a Product
? If there is a simple approach, does it still work with parallel streams?