OnJava8-Examples/patterns/trash/ParseTrash.java

69 lines
2.2 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/trash/ParseTrash.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
// Opens a file and parses its contents into
// Trash objects, placing each into a Fillable.
2016-07-28 12:48:23 -06:00
// {java patterns.trash.ParseTrash}
2015-06-15 17:47:35 -07:00
package patterns.trash;
import java.util.*;
2015-11-03 12:00:44 -08:00
import java.util.stream.*;
2015-06-15 17:47:35 -07:00
import java.io.*;
2015-09-07 16:34:48 -06:00
import java.nio.file.*;
2015-11-03 12:00:44 -08:00
import java.nio.file.Files;
2015-06-15 17:47:35 -07:00
public class ParseTrash {
public static String source = "Trash.dat";
2015-06-15 17:47:35 -07:00
public static <T extends Trash> void
fillBin(String packageName, Fillable<T> bin) {
DynaFactory factory =
new DynaFactory(packageName);
2015-06-15 17:47:35 -07:00
try {
Files.lines(Paths.get("trash", source))
// Remove comments and empty lines:
2015-11-03 12:00:44 -08:00
.filter(line -> line.trim().length() != 0)
.filter(line -> !line.startsWith("//"))
.forEach(line -> {
String type = line.substring(
2015-11-03 12:00:44 -08:00
0, line.indexOf(':')).trim();
2015-06-15 17:47:35 -07:00
double weight = Double.valueOf(
2015-11-03 12:00:44 -08:00
line.substring(line.indexOf(':') + 1)
.trim());
bin.addTrash(factory.create(
new TrashInfo(type, weight)));
2015-11-03 12:00:44 -08:00
});
} catch(IOException | NumberFormatException e) {
2015-06-15 17:47:35 -07:00
throw new RuntimeException(e);
}
}
// Special case to handle a List:
2015-06-15 17:47:35 -07:00
public static <T extends Trash> void
fillBin(String packageName, List<T> bin) {
fillBin(packageName, new FillableList<>(bin));
2015-11-03 12:00:44 -08:00
}
// Basic test:
public static void main(String[] args) {
List<Trash> bin = new ArrayList<>();
fillBin("trash", bin);
bin.forEach(System.out::println);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
2015-12-02 09:20:27 -08:00
/* Output:
Loading patterns.trash.Cardboard
2015-12-02 09:20:27 -08:00
Loading patterns.trash.Paper
Loading patterns.trash.Aluminum
Loading patterns.trash.Glass
Cardboard weight: 4.40 * price: 0.11 = 0.48
Paper weight: 8.00 * price: 0.10 = 0.80
Aluminum weight: 1.80 * price: 1.67 = 3.01
Glass weight: 5.40 * price: 0.23 = 1.24
Aluminum weight: 3.40 * price: 1.67 = 5.68
Cardboard weight: 2.20 * price: 0.11 = 0.24
Glass weight: 4.30 * price: 0.23 = 0.99
Cardboard weight: 1.20 * price: 0.11 = 0.13
Paper weight: 6.60 * price: 0.10 = 0.66
Aluminum weight: 2.70 * price: 1.67 = 4.51
Paper weight: 9.10 * price: 0.10 = 0.91
Glass weight: 3.60 * price: 0.23 = 0.83
2015-12-02 09:20:27 -08:00
*/